使用promise时出现此错误:
警告:无法在已卸载的组件上执行React状态更新。这是空操作,但它表明应用程序中发生内存泄漏。要修复,请取消使用useEffect清理功能中的所有订阅和异步任务。
我很确定这个错误是从我的诺言异步请求中得到的,当我不使用诺言时它工作正常。 但是当即时通讯使用诺言处理异步请求时,出现此错误,我需要诺言处理它,那么我该如何解决呢?
这是我的异步请求。
export const LoginAPI = (username, password) => (dispatch) => {
const config = {
headers: {
'Content-Type': 'application/json',
},
};
const body = JSON.stringify({ username, password });
const promise = new Promise((resolve, reject) => {
axios.post('http://localhost:8000/api/accounts/login/', body, config)
.then((response) => {
dispatch({ type: LOGIN_SUCCESS, payload: response.data });
SwalAlert('Successfully Login...', 'Welcome To 7Blankpages...', 'success');
resolve(true);
})
.catch((err) => {
dispatch({ type: LOGIN_FAILED });
if (err.response.data.non_field_errors) SwalAlert('Oops...', `${err.response.data.non_field_errors}`, 'error');
reject(false);
});
});
return promise;
};
这是我的登录处理
const handleSubmit = async (e) => {
e.preventDefault();
setIsLoading(true);
const response = await LoginUser(username, password).catch(() => setIsLoading(false));
if (response) {
setIsLoading(false);
setUsername('');
setPassword('');
}
};
if (auth.isAuthenticated && auth.user.is_active) {
return <Redirect to="/" />;
}
答案 0 :(得分:0)
发生这种情况的原因是您的handlesubmit函数是异步的,该函数使要执行的if块重定向到url'/'来更改组件。但是您的handlesubmit中的函数setisloading,setusername等仍将执行,从而导致内存泄漏。为了防止这种情况,请添加带有清理功能的useEffect挂钩。
MultipleObjectsReturned at /comment/268/
get() returned more than one UserPostComment -- it returned 2!