5

我的 componentDidMount 中有以下自动运行功能:

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

问题是另一个组件在未安装组件时更改了 this.props.data - 因此我在未安装的组件上收到 .setState 警告。

所以我想在组件卸载后删除自动运行。

我试着做:

componentWillUnmount() {
    this.autoUpdate = null
}

但是自动运行功能仍然会触发。一旦组件不再挂载,有没有办法取消 mobx 自动运行?

4

1 回答 1

10

autorun返回一个您需要调用才能取消它的处理程序函数。

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

  componentWillUnmount() {
    this.autoUpdateDisposer();
  }

  render() {
    // ...
  }
}
于 2017-04-25T09:43:34.583 回答