如何解决React:无法使用 Formik 对未安装的组件执行 React 状态更新
export const LoginForm = () => {
const [loading,setLoading] = React.useState(false);
const classes = useStyles();
const navigate = useNavigate();
const onSubmit = (values,actions) => {
setLoading(true);
axios({
method: 'POST',url: `localhost:3000/api/accounts/login`,data: values,headers: {
'CONTENT-TYPE': 'application/json'
}
})
.then(response => {
localStorage.setItem('user',JSON.stringify(response.data));
navigate('/',{ replace: true });
setLoading(false);
})
.catch(error => {
actions.setFieldError('general','Something went wrong');
actions.setSubmitting(false);
setLoading(false);
});
};
<Formik
initialValues={{ email: '',password: '' }}
validationSchema={Yup.object().shape({
email: Yup.string()
.email('Must be a valid email')
.max(255)
.required('Email is required'),password: Yup.string()
.max(255)
.required('Password is required')
})}
onSubmit={onSubmit}
>
}
我在控制台中收到以下消息,但不知道如何修复它
Warning: Can't perform a React state update on an unmounted component. This is a no-op,but it indicates a memory leak in your application. To fix,cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
in LoginForm (at routes.js:43)
in Outlet (at MainLayout/index.js:40)
in div (at MainLayout/index.js:39)
in div (at MainLayout/index.js:38)
in div (at MainLayout/index.js:37)
in div (at MainLayout/index.js:36)
in MainLayout (at routes.js:41)
我没有使用 useEffect
钩子,所以我不知道发生了什么
解决方法
确实如此,由于您没有使用 useEffect
钩子,因此该消息可能有点令人困惑,但是在卸载组件之后尝试更新状态的问题并不严格仅限于 useEffect
。任何异步处理的代码都可能导致此错误。我的猜测是在发出命令式导航后立即排队的状态更新。您导航到另一条路线,然后卸载此 LoginForm
组件。
我认为您可以在离开页面时删除 setLoading(false);
。
const onSubmit = (values,actions) => {
setLoading(true);
axios({
method: 'POST',url: `localhost:3000/api/accounts/login`,data: values,headers: {
'CONTENT-TYPE': 'application/json'
}
})
.then(response => {
localStorage.setItem('user',JSON.stringify(response.data));
navigate('/',{
replace: true
});
// remove the state update that was here
})
.catch(error => {
actions.setFieldError('general','Something went wrong');
actions.setSubmitting(false);
})
.finally(() => {
setLoading(false);
});
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。