jsx-eslint/eslint-plugin-react

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

Open

#2964 aperta il 11 apr 2021

Vedi su GitHub
 (12 commenti) (0 reazioni) (0 assegnatari)JavaScript (2797 fork)batch import
bughelp wanted

Metriche repository

Star
 (8630 star)
Metriche merge PR
 (Nessuna PR mergiata in 30 g)

Descrizione

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",
		},
	},
}

Guida contributor