React:无法使用 Formik 对未安装的组件执行 React 状态更新

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

我有以下组件。 onSubmit方法被调用

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 挂钩,但是尝试更新状态 after 组件的问题卸载并不严格限于 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);
    });
};