Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canceling mobx autorun function on componentWillUnmount

I have the following autorun function in my componentDidMount:

componentDidMount() {
        this.autoUpdate = autorun(() => {
            this.setState({
                rows: generateRows(this.props.data)
            })
        })
    }

The problem is that another component changes this.props.data when the component is not mount - and therefor I get the .setState warning on an unmounted component.

So I would like to remove the autorun once the component unmounts.

I tried doing:

componentWillUnmount() {
    this.autoUpdate = null
}

But the autorun function still triggers. Is there a way to cancel the mobx autorun once the component is not mounted any more?

like image 647
Miha Šušteršič Avatar asked Apr 25 '17 09:04

Miha Šušteršič


1 Answers

autorun returns a disposer function that you need to call in order to cancel it.

class ExampleComponent extends Component {
  componentDidMount() {
    this.autoUpdateDisposer = autorun(() => {
      this.setState({
        rows: generateRows(this.props.data)
      });
    });
  }

  componentWillUnmount() {
    this.autoUpdateDisposer();
  }

  render() {
    // ...
  }
}
like image 165
Tholle Avatar answered Sep 22 '22 21:09

Tholle