【问题标题】:Can't perform a React state update on an unmounted component when closing a material-ui modal by setting state通过设置状态关闭 Material-ui 模式时,无法对未安装的组件执行 React 状态更新
【发布时间】:2021-08-15 03:02:43
【问题描述】:

所以我使用了 material-UI 中的模态组件,并使用“打开”状态挂钩来控制其可见性。在这个组件中,我创建了一个登录页面组件,它将使用 Axios 发布信息并将打开状态设置为 false,从而关闭模式。我点击登录按钮后,控制台报告

无法对未安装的组件执行 React 状态更新。

这是我的代码:

function handleSubmit(e){
    e.preventDefault();
    AxiosInstance
        .post("/api/token/", account)
        .then((res)=>{
            localStorage.setItem('access_token', res.data.access);
            localStorage.setItem('refresh_token', res.data.refresh);
            AxiosInstance.defaults.headers['Authorization'] = 'Bearer '+localStorage.getItem('access_token');
            console.log(res);
            props.setOpen(false);
        })
        .catch((error)=>{
            
        })
}

【问题讨论】:

    标签: reactjs axios material-ui


    【解决方案1】:

    只需使用一个标志来解决这个问题,以便在 Axios 的 get 请求之外更改状态。

    function handleSubmit(e){
        e.preventDefault();
        const flag = false;
        AxiosInstance
            .post("/api/token/", account)
            .then((res)=>{
                localStorage.setItem('access_token', res.data.access);
                localStorage.setItem('refresh_token', res.data.refresh);
                AxiosInstance.defaults.headers['Authorization'] = 'Bearer '+localStorage.getItem('access_token');
                history.push("/#");
                history.push("/home");
                console.log(res);
                flag = true;
            })
            .catch((error)=>{
                
            })
            
        if (flag)
            props.setOpen(false);
    }
    

    但是,我仍然不明白 Axios 是如何工作的。似乎所有的状态变化都最好不要放在我的异步函数中。

    【讨论】:

    • 这就是异步函数的工作方式。最初,您将它放在 then() 中,这会在 promise 解决后发生。但是随着以后的实现,它发生在异步函数调用之后,它不会等到承诺解决。这就是为什么之前的错误在第二次没有发生的原因。
    猜你喜欢
    • 2021-11-09
    • 2021-07-01
    • 2020-11-21
    • 2023-02-11
    • 2019-11-09
    • 2019-05-30
    • 2021-05-30
    相关资源
    最近更新 更多