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

React登录页调用API报Cannot read properties of undefined (reading 'then')错误求助

解决React中API调用的Uncaught TypeError: Cannot read properties of undefined (reading 'then')错误

问题根源

你的authorise方法没有返回axios请求生成的Promise对象。虽然方法内部执行了axios.post,但你没有把这个Promise返回出去,导致外部调用api.authorise(...).then()时,实际上是在undefined上调用.then,自然触发类型错误。

修复方案

方案1:直接返回axios请求结果

axios的post方法本身就返回Promise,你不需要在方法内部额外包裹.then/.catch,直接返回这个Promise即可:

authorise(email, password, appid) {
    this.email = email;
    this.password = password;
    this.appid = appid;

    let url = "api url";

    const data = {
        "data1": email,
        "data2": password,
        "data3": appid
    }

    // 关键:返回axios请求的Promise
    return axios.post(url, data);
}

对应的调用代码可以保留原有结构,同时补充错误捕获:

const api = new API();
api.authorise(email, password, appid)
    .then((result) => {
        console.log("Auth Successful");
        return result;
    })
    .catch((err) => {
        console.log("Auth Failed");
        return err.response || err;
    });

方案2:用async/await重构(更易读)

如果你习惯异步代码的同步写法,可以把authorise改成async方法:

async authorise(email, password, appid) {
    this.email = email;
    this.password = password;
    this.appid = appid;

    let url = "api url";

    const data = {
        "data1": email,
        "data2": password,
        "data3": appid
    }

    try {
        const res = await axios.post(url, data);
        return res;
    } catch (err) {
        // 这里可以根据需要处理错误,比如返回错误信息
        return err;
    }
}

调用时同样使用async/await(注意要在async函数内执行):

const handleLogin = async () => {
    const api = new API();
    try {
        const result = await api.authorise(email, password, appid);
        console.log(result.status === 200 ? "Auth Successful" : "Auth Failed");
        return result;
    } catch (err) {
        console.log("Auth Failed with error:", err);
        return err;
    }
}

补充说明

你之前尝试把authorise改成箭头函数,这是用来解决类方法中this指向丢失的问题,但本次错误的根源并非this,而是方法没有返回值,所以箭头函数无法解决这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:20:26