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

React类组件调用setState报Cannot read properties of undefined错如何解决?

报错原因

TypeError: Cannot read properties of undefined (reading 'setState') 是因为类组件中普通定义的方法 setEmailVal 没有绑定组件实例的 this 指向,当它作为输入框的 onChange 回调被触发时,方法内部的 this 指向为 undefined,因此无法调用挂载在组件实例上的 setState 方法。

解决方案

可选择以下任意一种方式修复:

方案1:构造函数内手动绑定this

在类的构造函数中给方法绑定当前组件实例的this:

import React from 'react';

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {email: ""};
        // 新增绑定代码
        this.setEmailVal = this.setEmailVal.bind(this);
    }

    setEmailVal(val) {
        this.setState({email: val.currentTarget.value});
    }

    render() {
        return (
            <input type="text" onChange={this.setEmailVal} value={this.state.email} />
        );
    }    
}

export default Login;

方案2:用箭头函数定义类方法

箭头函数会自动继承外层上下文的this,无需手动绑定:

import React from 'react';

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {email: ""};
    }

    // 改为箭头函数写法
    setEmailVal = (val) => {
        this.setState({email: val.currentTarget.value});
    }

    render() {
        return (
            <input type="text" onChange={this.setEmailVal} value={this.state.email} />
        );
    }    
}

export default Login;

方案3:回调绑定时用箭头函数包裹

在onChange绑定处直接用箭头函数包裹原方法,确保方法执行时的this指向组件实例:

import React from 'react';

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {email: ""};
    }

    setEmailVal(val) {
        this.setState({email: val.currentTarget.value});
    }

    render() {
        return (
            {/* 改为箭头函数包裹调用 */}
            <input type="text" onChange={(e) => this.setEmailVal(e)} value={this.state.email} />
        );
    }    
}

export default Login;

注意:该方案每次组件渲染都会生成新的函数实例,若作为props传递给子组件可能触发不必要的重渲染,简单场景可正常使用。

内容的提问来源于stack exchange,提问作者Pankaj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:36:08