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

React Class Component onClick调用setState报undefined错误排查

问题根因

你看到的cannot set properties of undefined setting set state报错和功能失效,来自代码里的4处写法错误,报错指向super(props)只是源码映射的位置偏差,和super调用本身无关:

  • 错误用法1:setState是React类组件内置的实例方法,你写的this.setState=({response : "This is not a valid tracking #"})是给实例新增属性覆盖内置方法,根本不是执行状态更新。正确调用方式是直接传参:this.setState(/* 新状态对象 */),中间不要加等号。
  • 错误用法2:类的普通原型方法默认不会绑定this指向,你直接把this.autoResponse传给onClick时,事件触发时方法内部的this是undefined,自然访问不到setState方法,这是触发报错的核心原因。
  • 错误用法3:文件顶部声明的全局response变量、componentDidMount里给全局变量赋值的代码完全多余,类组件的视图相关状态统一存在this.state中即可,额外定义全局变量不会触发视图重渲染,写了也没用。
  • 错误用法4:之前尝试调用preventDefault()提示未定义,是因为你没有接收事件参数,事件回调默认会传入事件对象作为第一个参数,接收后就能正常调用。
可直接运行的修正代码
import React,{Component} from "react";

class Track extends Component{
    constructor(props) {
        super(props)
        // 初始化状态
        this.state = {
            response: "",
        };
        // 手动绑定方法的this指向
        this.autoResponse = this.autoResponse.bind(this);
    }

    autoResponse(e){
        // 正确调用setState更新状态
        this.setState({
            response: "This is not a valid tracking #"
        })
        // 需要阻止默认行为时解开下面注释即可
        // e.preventDefault()
    }
     
    render(){  
        return(
            <>
                <input placeholder="Enter Tracking #" />
                <button onClick={this.autoResponse}>TRACK</button>
                <div className="response-cntr">
                    <p className="response-text">{this.state.response}</p>
                </div>
            </>
        )
    }
}

export default Track;
简化写法(无需手动绑定this)

现在类组件更常用箭头函数类字段的写法定义事件回调,可以省掉constructor里的bind步骤,利用箭头函数继承上层作用域this的特性避免指向丢失:

import React,{Component} from "react";

class Track extends Component{
    state = {
        response: "",
    }

    // 箭头函数写法,不需要手动bind
    autoResponse = () => {
        this.setState({
            response: "This is not a valid tracking #"
        })
    }
     
    render(){  
        return(
            <>
                <input placeholder="Enter Tracking #" />
                <button onClick={this.autoResponse}>TRACK</button>
                <div className="response-cntr">
                    <p className="response-text">{this.state.response}</p>
                </div>
            </>
        )
    }
}

export default Track;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 01:09:26