jsx-eslint/eslint-plugin-react

no-access-state-in-setstate false negative in async class method

Open

#2.964 aberto em 11 de abr. de 2021

Ver no GitHub
 (12 comments) (0 reactions) (0 assignees)JavaScript (2.797 forks)batch import
bughelp wanted

Métricas do repositório

Stars
 (8.630 stars)
Métricas de merge de PR
 (Nenhuma PRs mesclada em 30d)

Description

I'm getting a false positive from the no-access-state-in-setstate rule with this method in a class component:

async onSubmit(event) {
	event.preventDefault()
	this.setState({ submitting: true })

	const res = await fetchJSON(
		"/api/user",
		"POST",
		this.state.values, // error: "Use callback in setState when referencing the previous state."
	)

	if (!res.error) {
		return this.props.router.push("/")
	}

	this.setState({
		submissionError: res.error,
		submitting: false,
	})
}

If I rewrite that as fetchJSON(...).then(res => ...) the error goes away. (It actually goes away if I just remove the const res = part, but then I can't use the returned value.)

  • eslint 7.24.0
  • eslint-plugin-react 7.23.2

Here's my ESLint configuration:

module.exports = {
	env: {
		browser: true,
		commonjs: true,
		es2021: true,
		node: true,
	},
	extends: [
		"eslint:recommended",
		"plugin:react/recommended",
	],
	parserOptions: {
		ecmaVersion: 2021,
		sourceType: "module",
		ecmaFeatures: {
			jsx: true,
		},
	},
	plugins: [
		"react",
	],
	rules: {
		// ...
		"react/button-has-type": 2,
		"react/jsx-child-element-spacing": 2,
		"react/jsx-curly-brace-presence": [1, "never"],
		"react/jsx-curly-newline": [1, "consistent"],
		"react/jsx-curly-spacing": [1, { when: "never", allowMultline: true }],
		"react/jsx-equals-spacing": [1, "never"],
		"react/jsx-first-prop-new-line": [1, "multiline-multiprop"],
		"react/jsx-indent": [1, "tab"],
		"react/jsx-no-script-url": 2,
		"react/jsx-no-target-blank": 1,
		"react/jsx-no-useless-fragment": 1,
		"react/jsx-props-no-multi-spaces": 1,
		"react/jsx-tag-spacing": [1, { beforeClosing: "never", beforeSelfClosing: "always" }],
		"react/jsx-wrap-multilines": 1,
		"react/no-access-state-in-setstate": 2,
		"react/no-adjacent-inline-elements": 2,
		"react/no-unused-prop-types": 2,
		"react/no-unused-state": 2,
		"react/prop-types": 0,
		"react/self-closing-comp": 1,
		"react/state-in-constructor": 2,
	},
	settings: {
		react: {
			version: "detect",
		},
	},
}

Guia do colaborador