Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warning: Can't call setState (or forceUpdate) 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 the componentWillUnmount method. #772

Closed
josoroma-zz opened this issue Jul 18, 2018 · 7 comments
Labels

Comments

@josoroma-zz
Copy link

josoroma-zz commented Jul 18, 2018

How to automatically unsubscribe after we have a response?

const formikOptions = formikConfig({
  mapPropsToValues: props => ({
    email: '',
    password: '',
  }),
  validationSchema: Yup.object().shape({
    password: validations.passwordRequired,
    email: validations.email(),
  }),
  handleSubmit: (values, { props, setErrors }) => {
    const auth = new Auth();

    auth.signIn(values.email, values.password)
      .subscribe(
        data => {
          if (data.cognitoUser.challengeName === 'NEW_PASSWORD_REQUIRED') {
            history.push(paths.newPasswordChallenge);
          }
        }
      );
  },
});

Thanks in advance!

@JamieLivingstone
Copy link

Hi @josoroma,

I can not see all of your code so I am making a couple of assumptions, this looks like a login form and I'm assuming that you are redirecting on successful authentication? And after the redirect something within the component is setting state.

Kent C. Dodds recently did a video which shows you how to prevent this from happening here:
https://www.youtube.com/watch?v=8BNdxFzMeVg (Avoid setState warnings on unmounted React components)

The simplest way to prevent the warning would be to do the following:
componentDidMount() -> set a property _isMounted to true
componentWillUnmount() -> set the _isMounted to false

and before you call the setState wrap it in a conditional to make sure the component is mounted :)

@danielwong2268
Copy link

I thought this was fixed here?

#756

I am getting this same still when unmounting the form after submission

@jaredpalmer
Copy link
Owner

Hrmmm

@typical000
Copy link

Hi! I'm having same error. I'm using formik together with react-apollo.

Truncated example of code:

<Query query={FOO_QUERY}>
  {({data}) => {
    if (data.foo.someFlag) {
      return <Foo>;
    }

    return (
      <ApolloConsumer>
        {({mutate}) => (
          <Formik
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={(payload, {setSubmitting, setErrors}) => {
              mutate({
                mutation: FOO_MUTATION,
                variables: payload,
                update: (cache, {data: {foo}}) => {
                  const data = cache.readQuery({query: FOO_QUERY});
                  data.foo.someFlag = foo.someFlag;
                  cache.writeQuery({
                    query: FOO_QUERY,
                    data,
                  });
                }
              })
                .then((response) => {
                  const {limitReached} = response.data.feedback;
                  const errors = normalizeMutationErrors(
                    response.data.feedback.errors,
                  );

                  setSubmitting(false);
                  setErrors(errors);

                  // ... do other stuff
                })
            }}
          >
            {({handleSubmit, isSubmitting}) => (
              <Form
                categories={CATEGORIES}
                showHelpLink={showHelpLink}
                loading={isSubmitting}
                onSubmit={handleSubmit}
              />
            )}
          </Formik>
        )}
      </ApolloConsumer>
    )
  }}
</Query>

Debugger sends me inside 'formik.esm.js' on this line:

_this.setSubmitting = function (isSubmitting) {
    _this.setState({ isSubmitting: isSubmitting });
};

As I see, mutation update method is called before all Formik submitting process ends,
and when my apollo cache was already updated - entire <Formik> component goes unmounted and <Foo> component start rendering.
And, Formik setState was called after component is unmounted

@macbem
Copy link

macbem commented Aug 20, 2018

I had a similar case where I had a try / catch block over an awaited thunk action. In the try block, I redirected the user to another route after the action succeeded, so the form component was unmounted, but then, I used setSubmitting in the finally block, which caused the error to show up.

@stale
Copy link

stale bot commented Oct 19, 2018

Hola! So here's the deal, between open source and my day job and life and what not, I have a lot to manage, so I use a GitHub bot to automate a few things here and there. This particular GitHub bot is going to mark this as stale because it has not had recent activity for a while. It will be closed if no further activity occurs in a few days. Do not take this personally--seriously--this is a completely automated action. If this is a mistake, just make a comment, DM me, send a carrier pidgeon, or a smoke signal.

@stale stale bot added the stale label Oct 19, 2018
@stale
Copy link

stale bot commented Oct 26, 2018

ProBot automatically closed this due to inactivity. Holler if this is a mistake, and we'll re-open it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

6 participants