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

React报错TypeError: Cannot read properties of undefined (reading 'state')如何解决?

React onClick TypeError 问题修复方案
  • 问题1:类方法this指向丢失
    类组件中直接将this.authenticate绑定给onClick事件时,方法执行时内部this不会指向组件实例,访问this.state会直接抛出TypeError。
    修复可选方案二选一:

    1. 在构造函数中绑定this:
    constructor(props) {
      super(props);
      this.state = {username: '', password: ''};
      // 新增绑定逻辑
      this.authenticate = this.authenticate.bind(this);
    }
    
    1. 直接将authenticate定义为类属性箭头函数:
    authenticate = (e) => {
      // 原有逻辑不变
    }
    
  • 问题2:onChange回调参数使用错误
    原生input的onChange回调仅接收1个event参数,不存在第二个newValue参数,你当前的写法会导致state里的username、password全部被赋值为undefined。
    修复方式改为从event.target.value取值:

    <input 
      type="email" 
      onChange = {(event) => this.setState({username:event.target.value})} 
      className="form-control" 
      name="email" 
      placeholder="Enter your Email" 
      required="required" 
    />
    
    <input 
      type="password" 
      onChange = {(event) => this.setState({password:event.target.value})} 
      className="form-control" 
      name="password" 
      placeholder="Enter your Password" 
      required="required" 
    />
    
  • 问题3:对象属性访问不匹配
    你定义的details对象中,邮箱对应的键是email,后续调用details.username会返回undefined。
    修复方式:

    authenticate(e){
      e.preventDefault();
      var details = {
          "email" : this.state.username,
          "password" : this.state.password
      }
      // 修改属性名匹配
      alert(details.email + details.password);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:36:00