TypeError: 无法读取 undefined 的属性 'setState'
TypeError: Cannot read properties of undefined (reading 'setState')
ID: react/error-cannot-read-properties-of-undefined-reading-setstate
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 18.2.0 | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 16.14.0 | active | — | — | — |
根因分析
类组件试图调用 this.setState,但 'this' 是 undefined,通常是因为方法没有绑定到实例或组件没有正确实例化。
English
A class component is trying to call this.setState but 'this' is undefined, typically because the method is not bound to the instance or the component is not properly instantiated.
官方文档
https://react.dev/reference/react/Component#setstate解决方案
-
Bind the method in the constructor: constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } -
Use class property arrow functions: handleClick = () => { this.setState(...); } -
Convert the class component to a function component with useState hook to avoid 'this' issues entirely.
无效尝试
常见但无效的做法:
-
Use arrow functions in JSX event handlers without binding
80% 失败
Arrow functions in JSX create a new function on every render, causing performance issues and still not fixing the 'this' context if the method is not bound.
-
Call setState as a standalone function without 'this'
100% 失败
setState is a class instance method and must be called on 'this'; calling it standalone will throw a different error.
-
Use functional setState syntax (prevState => newState) but still without binding
95% 失败
The functional syntax doesn't solve the 'this' binding issue; the method still needs to be called on the correct context.