You need to enable JavaScript to run this app. React.js执行getData时报Cannot read property 'username' of undefined问题问询
优惠活动
大模型
产品
解决方案
定价
更多

React.js执行getData时报Cannot read property 'username' of undefined问题问询

报错原因

$.ajax的beforeSend回调使用了普通函数声明,普通函数的this指向由运行时的调用方决定,该回调执行时this不指向当前React组件实例,导致this.state为undefined,读取this.state.username时就抛出了对应错误。
即便你已经给getData方法绑定了组件实例的this,普通函数形式的回调内部的this也不会继承外层getData的this指向。

修复方案

推荐优先使用方案1,改动最小且符合现代JS编码习惯:

方案1:将回调改为箭头函数

箭头函数的this会继承外层作用域的this指向,直接替换beforeSend和success的普通函数即可:

getData() {
    $.ajax({
        type: 'GET',
        url: `/home/data`,
        dataType: 'json',
        beforeSend: (xhr) => {
            xhr.setRequestHeader('Authorization', make_base_auth(this.state.username, this.state.password));
        },
        success: (xhr) => {
            console.log(xhr.status)
        }
    });
}

方案2:外层提前保存组件this

在getData开头先将组件实例的this存储到临时变量,回调内使用该变量访问状态:

getData() {
    const component = this;
    $.ajax({
        type: 'GET',
        url: `/home/data`,
        dataType: 'json',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', make_base_auth(component.state.username, component.state.password));
        },
        success: function(xhr){
            console.log(xhr.status)
        }
    });
}

方案3:给回调手动绑定this

给beforeSend和success回调手动绑定当前组件实例的this:

getData() {
    $.ajax({
        type: 'GET',
        url: `/home/data`,
        dataType: 'json',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', make_base_auth(this.state.username, this.state.password));
        }.bind(this),
        success: function(xhr){
            console.log(xhr.status)
        }.bind(this)
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 19:15:04