无法对卸载的组件执行 React 状态更新 - 表示内存泄漏

时间:2021-07-27 03:29:16

标签: reactjs

在 Login 组件中,我调用了 login 函数来期望异步行为。

    const handleSubmit = async (e) => {
    e.preventDefault()
    
    if (usernameRef.current.value === "" || passwordRef.current.value === "") {
        return setError('username or password field should not be empty')
    }

    setError('')
    setLoading(true)
    try {
        const res = await login(usernameRef.current.value, passwordRef.current.value)
        localStorage.setItem("token", res.data.access_token)
        history.push("/")
        setLoading(false)
    } catch {
        setError('Could not login')
        setLoading(false)
    }
}

在 authContext 中,我在下面写了这两个:

useEffect(() => {
    const unsubscribe = axios.get("http://127.0.0.1:8000/api/users/me", {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem("token")}`
            },
        }).then((res) => {
            console.log(res.statusText)
            setCurrentUser(res.data)
            setLoading(false)
        }).catch((err) => {
            console.log(err)
        })
    
    return unsubscribe
}, [])

const login = async (username, password) => {
    const details = {
        "username": username,
        "password": password
    }
    let formBody = [];
    for (let property in details) {
        let encodedKey = encodeURIComponent(property);
        let encodedValue = encodeURIComponent(details[property]);
        formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");

    return await axios.post("http://127.0.0.1:8000/login", formBody, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        }
    })
}

抓取有问题吗?每当我登录时,它确实登录成功,但出现错误,指示要修复,取消 useEffect 清理函数中的所有订阅和异步任务。

0 个答案:

没有答案