How to stop callback from unmounting component

In fact, this is confused. I updated for React Router 4 which required a few changes and now when my server-side registration errors return a console error: it's a callback.

setState (...): Can only update mounted or mounted component. This usually means that you called setState () on an unmounted component. This is a no-op. Check the code for the RegisterForm component.

What's really confusing is if I run this.setState({ errors: {createUserError: "Test error" }});

outside of the function Accounts.createUser

, I don't get the console error.

Any suggestions????

handleSubmit(event) {
    event.preventDefault();

    this.setState({errors: {} }, function() {
      var data = {
        email: this.state.email,
        password: this.state.password
      };

        Accounts.createUser(data, (error) => {   // This arrow function preserves this
        if(error) {
          this.setState({ errors: {createUserError: error.reason }});
        }
      });
    });
  }

      

+3


source to share


1 answer


By the time the HTTP request generated by using Accounts.createUser

returns an error, the component that is bound to handleSubmit

is disabled, so the call setState

generates an error.

One option is to move handleSubmit

to a parent that will not be unmounted on form submission and pass the function down as a prop. Another option is to use abbreviation or stream for state management.



Another option is to keep the component until Accounts.createUser

it returns successfully, which will allow you to display messages on the form in case of an error. For example, you can specify which fields are invalid.

+2


source







All Articles