【问题标题】:axios: Unhandled Rejection (TypeError): Cannot read property 'error' of undefinedaxios:未处理的拒绝(TypeError):无法读取未定义的属性“错误”
【发布时间】:2020-06-14 20:53:09
【问题描述】:

我正在尝试使用 axios 发出 POST 请求。以下是我在名为 userFunctions.js 的文件中的 axios 函数。

export const savePost = (postInfo) => {
    return axios
        .post(
            "admin/savepost",
            { first_name: "hello", last_name: "world" },
            {
                headers: {
                    Authorization: `Bearer ${localStorage.usertoken}`,
                },
            }
        )
        .then((response) => {
            console.log(response); //response is able to get printed here
            console.log("axios:: saved post");
        });
};

我在另一个名为 card.js 的文件中调用它,如下所示:

handleChange(e) {
        e.preventDefault();
        const { name, type, checked } = e.target;
        if (type === "checkbox") {
            this.setState({
                [name]: checked,
            });
            savePost("post 1").then((res) => {
                //response is undefined here!
                console.log(res === undefined); //true

                if (!res.error) {
                    console.log("client: post saved");
                }
            });
        }
    }

我收到以下错误:

未处理的拒绝 (TypeError):无法读取属性“错误”的 未定义

我不明白为什么响应能够在 userFunctions.js 中打印但在我调用 card.js 中的 savePost 变量时未定义

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

    发生这种情况是因为您在 userFunctions.js 中处理响应并且没有将其返回(即您的承诺链中的最后一个 then 返回未定义)。 进行以下更改:

        .then((response) => {
            console.log(response); //response is able to get printed here
            console.log("axios:: saved post");
            return response
        });
    

    【讨论】:

    • 嘿,谢谢你的帮助。这就是问题所在。
    猜你喜欢
    • 2020-04-29
    • 2021-08-16
    • 2021-01-13
    • 2019-04-07
    • 2021-12-13
    • 2021-05-06
    • 2019-07-19
    • 2019-06-03
    • 2020-04-09
    相关资源
    最近更新 更多