带有onSubmit异步调用的Formik表单组件的警告消息:取消useEffect清理功能中的所有订阅和异步任务

时间:2020-09-25 23:13:37

标签: asynchronous memory-leaks react-hooks formik

我认为我了解此问题的概念,但是由于该组件中没有useEffect,因此我不确定该如何“清理”:

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 Formik (at LoginForm.js:19)
    in LoginForm (created by Context.Consumer)
    in withRouter(LoginForm) (at LandingPage.js:17)
    in div (at LandingPage.js:16)
    in div (at LandingPage.js:15)
    in div (at LandingPage.js:9)
    in div (at LandingPage.js:8)
    in LandingPage (created by Context.Consumer)
    in Route (at App.js:33)

表单看起来像这样:

// imports...

const LoginForm = (props) => {
  const { setAuthStatus } = useContext(AuthContext);
  const { setUserData } = useContext(UserContext);

  return (
    <Formik
      initialValues={...}
      validate={...}
      onSubmit={(values, actions) => {
        const config = {
          baseURL: '/api/auth/login',
          method: 'post',
          withCredentials: true,
          headers: {
            'Content-Type': 'application/json',
          },
          data: values,
        };

        axios(config).then((res) => {
          setAuthStatus('verified');
          localStorage.setItem('authstatus', 'verified');
          props.history.push('/users/dashboard');
        }).catch((error) => {
          actions.setStatus({
            server: error,
          });
          localStorage.setItem('authstatus', 'unverified');
        }).finally(() => actions.setSubmitting(false));
      }}
    >
      {({ isSubmitting, errors }) => (
        <Form id="loginform">
          ...
        </Form>
      )}
    </Formik>
  );
};

export default withRouter(LoginForm);

因此问题似乎是,当此LoginForm安装在页面上,然后在api调用仍处于活动状态时页面更改或“卸载”时,可能会造成内存泄漏。

我知道您可以在useEffect中返回一个函数以进行清理,但是在我这种情况下没有useEffect的情况下,该怎么解决?

0 个答案:

没有答案