admin管理员组

文章数量:1302230

I have the following autorun function in my ponentDidMount:

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

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

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

I tried doing:

ponentWillUnmount() {
    this.autoUpdate = null
}

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

I have the following autorun function in my ponentDidMount:

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

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

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

I tried doing:

ponentWillUnmount() {
    this.autoUpdate = null
}

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

Share Improve this question edited Apr 25, 2017 at 9:43 Tholle 113k22 gold badges208 silver badges197 bronze badges asked Apr 25, 2017 at 9:29 Miha ŠušteršičMiha Šušteršič 10.1k27 gold badges97 silver badges175 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

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

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

  ponentWillUnmount() {
    this.autoUpdateDisposer();
  }

  render() {
    // ...
  }
}

本文标签: javascriptCanceling mobx autorun function on componentWillUnmountStack Overflow