首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在componentWillUnmount上取消mobx自动运行功能

问在componentWillUnmount上取消mobx自动运行功能
EN

Stack Overflow用户
提问于 2017-04-25 09:29:35
回答 1查看 2.9K关注 0票数 5

我的componentDidMount中有以下自动运行函数:

代码语言:javascript
复制
componentDidMount() {
        this.autoUpdate = autorun(() => {
            this.setState({
                rows: generateRows(this.props.data)
            })
        })
    }

问题是,当组件没有挂载时,另一个组件会更改this.props.data --为此,我在未挂载的组件上得到.setState警告。

因此,一旦组件卸载,我想删除自动运行。

我试着做:

代码语言:javascript
复制
componentWillUnmount() {
    this.autoUpdate = null
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-25 09:43:34

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

代码语言:javascript
复制
class ExampleComponent extends Component {
  componentDidMount() {
    this.autoUpdateDisposer = autorun(() => {
      this.setState({
        rows: generateRows(this.props.data)
      });
    });
  }

  componentWillUnmount() {
    this.autoUpdateDisposer();
  }

  render() {
    // ...
  }
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43606744

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档