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

React causing: Can't perform a React state update on an unmounted component

我的情况:登录后我尝试获取用户名并在从登录重定向到主页后将其保存到 redux 存储(在此页面中我显示任务列表)并且我得到:无法执行在未安装的组件上响应状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。

我尝试了常用的 isMounted 技巧,但没有用。

Login.js

function getUsername(){
    let username = ""
    const headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    };

    try {
        axios.get(`${process.env.REACT_APP_API_URL}/api/get_username/`,{
                headers: headers,
            })
            .then(response => username = response.data["username"])
            .catch(error => setResponse(error.response))
    } catch (err) {
        console.log(err)
    }

    return username
}

const loginSubmit = e => {
    e.preventDefault()
    const headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'X-CSRFToken': csrftoken,
    };
    const body = {username: username, password: password}
    try {
        axios.post(`${process.env.REACT_APP_API_URL}/api/login/`, body,{
                headers: headers,
            })
            .then(response => setResponse(response))
            .catch(error => setResponse(error.response))
    } catch (err) {
        console.log(err)
    }

    dispatch({type: "SET_NAME", name:getUsername()})
    Cookies.set("logged_in", "yes")

    navigate("/", {replace:true})
};

Home.js

function getTasks(isMounted){
    const headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    };
    try {
        axios.get(`${process.env.REACT_APP_API_URL}/api/tasks/`, {
            headers: headers,})
            .then(response => {if(isMounted ){setTasks(response.data)}})
            .catch(error => setTasks(error.response))
    } catch (err) {
        console.log(err)
    }
}

useEffect(() => {
    let isMounted = true;
    getTasks(isMounted);
    return () => {
        isMounted = false;
    };
}, []);

您可以使用本地存储。

设置项目:

localStorage.setItem("name", JSON.stringify(name))

获取物品:

localStorage.getItem("name")