简体   繁体   中英

setState Can only update a mounted or mounting component

I have a login component where when user submits the login form, i get an error of

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.

I could not even find where this error is

class LoginForm extends React.Component {
  state = {
    identifier: '',
    password: '',
    errors: {},
    isLoading: false
  };

  static contextTypes = {
    router: PropTypes.object.isRequired
  };

  isValid = () => {
    const { errors, isValid } = validateInput(this.state);
    if (!isValid) {
      this.setState({ errors });
    }
    return isValid;
  };

  onSubmit = (e) => {
    e.preventDefault();
    if (this.isValid()) {
      this.setState({ errors: {}, isLoading: true });
      const loginDetails = Object.assign({}, {identifier: this.state.identifier, password: this.state.password});
      this.props.login(loginDetails).then(res => {
        console.log('res', res);
        return this.context.router.push('/');
      }).catch(error => {
        return this.setState(Object.assign({}, this.state, error, {isLoading: false}));
      });
    }
  };

  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  render() {
    const { errors, identifier, password, isLoading } = this.state;
    return (
      <form onSubmit={this.onSubmit}>
        <fieldset>
          <legend>Login</legend>
          { errors.form && <div className="alert alert-danger">{errors.form}</div> }
          <TextFieldGroup
            name="identifier"
            label="Username / Email"
            value={identifier}
            error={errors.identifier}
            onChange={this.onChange}
          />
          <TextFieldGroup
            name="password"
            label="Password"
            value={password}
            error={errors.password}
            onChange={this.onChange}
            type="password"
          />
          <div className="form-group">
            <button className="btn btn-primary btn-lg" disabled={isLoading}>Login</button>
          </div>
        </fieldset>
      </form>
    );
  }
}

export default connect(null, { login })(LoginForm);

where exactly is the error?

You are running this async code with that promise call:

onSubmit = (e) => {
    e.preventDefault();
    if (this.isValid()) {
      this.setState({ errors: {}, isLoading: true });
      const loginDetails = Object.assign({}, {identifier: this.state.identifier, password: this.state.password});
      this.props.login(loginDetails).then(res => {
        console.log('res', res);
        return this.context.router.push('/');
      }).catch(error => {
        return this.setState(Object.assign({}, this.state, error, {isLoading: false}));
      });
    }
  };

so whenever the promise fails it calls setState . This code will run even if your component isn't mounted anymore.

There's some documentation and a suggestion to overcome the promise issue here https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html

And this library seem to wrap promises with a decorator - I'm not suggesting you to use it, it's just a good way of understanding what's going on.

BTW, this is a good reason to use redux .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM