简体   繁体   中英

setState(…): Can only update a mounted or mounting component

This is the code. No idea as to why there is a problem.

class TeacherForm extends Component {
  constructor({ data }) {
    super();

    this.isUpdatingForm = !! data;
    this.state = Object.assign({ ... });

    this.handleSubmit = this.handleSubmit.bind(this);
    this.removeTeacher = this.removeTeacher.bind(this);
  }

  handleChange(value, field) {
    this.setState({ shouldUpdate: true, [field]: value });
  }

  handleSubmit(e) {
    e.preventDefault();
    const { name, subjects, parttime, timing } = this.state;

    if (this.isUpdatingForm) {
      return update.call({
        _id: this.props.data._id,
        transaction: { name, subjects, parttime, timing },
      }, () => this.setState({ shouldUpdate: false }));
    }

    return add.call();
  }

  removeTeacher() {
    return remove.call(this.props.data._id);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
         ...
      </form>
    );
  }
}

The error gets thrown at the handleSubmit method in the callback of update.call . This normally shows up when I call removeTeacher and a list updates and this component unmounts.

It sounds like the callback () => this.setState({ shouldUpdate: false }) is executed after that the component is unmounted. Is that possible? If so, one way to get around that is to replace this part by

return update.call({
  _id: this.props.data._id,
  transaction: { name, subjects, parttime, timing },
}, () => { !this.unmounted && this.setState({ shouldUpdate: false }); });

and to add

componentWillUnmount() {
  this.unmounted = true;
}

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