You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React类组件TypeError: Cannot read properties of undefined (reading 'state')求助

解决React类组件中this.state未定义的TypeError问题

问题核心:React类组件的自定义方法默认不会自动绑定组件实例的this,当你将this.changeBg作为onMouseOver事件回调传递时,方法内部的this丢失了指向,导致访问this.state时抛出Cannot read properties of undefined (reading 'state')错误。

下面是三种可行的解决方法:

1. 在构造函数中手动绑定this

在组件的constructor里,把自定义方法的this绑定到组件实例上:

class GenresInDb extends Component {
    constructor() {
        super()
        this.state = {
            genresList: [],
            genreBg: "",
        }
        // 绑定changeBg方法的this到当前组件实例
        this.changeBg = this.changeBg.bind(this);
    };
    // 其余代码不变
}

2. 使用箭头函数作为事件回调

在onMouseOver属性中直接用箭头函数包裹方法调用,箭头函数会继承当前render方法的this指向(即组件实例):

// 修改render中的h6标签
<h6 onMouseOver={() => this.changeBg()} className="m-0 font-weight-bold text-gray-800">Genres in Data Base</h6>

3. 用Class Fields语法定义箭头函数方法

将changeBg方法直接定义为箭头函数,这样this会自动绑定到组件实例:

// 修改changeBg方法
changeBg = () => {
    if(this.state.genreBg === ""){
        this.setState({
            genreBg: "bg-secondary"
        })
    } else {
        this.setState({
            genreBg: ""
        })
    }
}

各方案说明

  • 构造函数绑定:传统且稳定的方式,只会在组件初始化时绑定一次,没有额外性能开销。
  • 箭头函数回调:写法简单,但每次组件渲染都会创建新的箭头函数,若组件频繁渲染可能有轻微性能影响,适合小型组件。
  • Class Fields箭头函数:ESNext语法,Create React App等现代脚手架默认支持,写法简洁且自动绑定this,是当前推荐的方式之一。

内容的提问来源于stack exchange,提问作者Juan Manuel Zimmermann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 22:33:33