繁体   English   中英

组件已安装,但我无法调用this.setState(...)或this.forceUpdate(...);

[英]Component is mounted but I can't call this.setState(…) or this.forceUpdate(…);

我正在使用可滚动的标签视图和facebook官方助焊剂解决方案。 有些场景保持不活动状态(不是当前选中的选项卡)并从商店接收需要更新场景的事件,但我有这样的错误: Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.

我已经双重检查,并且没有调用componentWillUnmount() ..但是我收到此警告,我无法更新组件的状态。

这里我有一些组件的示例代码,该问题存在于未选中的选项卡中:

 constructor(props) {
    super(props);

    this.state = {
      isFavorite: this.isCurrentPostFavorite,
      isMounted: false,
      value: 0,
    };

    this.updateStateForFavoriteModification = this.updateStateForFavoriteModification.bind(this);
  }

  componentDidMount() {
    this.setState({isMounted: true});
    console.log('Article Scene did mount for article: '.toUpperCase() + this.props.sceneInfo.article.name);
    HotelStore.bind(HotelEvent.didModifiedFavorite, this.updateStateForFavoriteModification.bind(this));
  }

  componentWillUnmount() {
    this.setState({isMounted: false});
    console.log('Article Scene will unmount for article: '.toUpperCase() + this.props.sceneInfo.article.name);
    HotelStore.unbind(HotelEvent.didModifiedFavorite, this.updateStateForFavoriteModification);
  }

  changeFavoriteStatus() {
    if (this.state.isFavorite) {
      sendAction(HotelAction.removeFavorite, this.props.sceneInfo.article);
    }
    else {
      sendAction(HotelAction.addFavorite, this.props.sceneInfo.article);
    }
  }

  updateStateForFavoriteModification() {
    console.log('Update: '.toUpperCase() + this.props.sceneInfo.article.name);
    console.log('isMounted: '.toUpperCase() + this.state.isMounted);

    //
    //
    // Here I Get the error
    this.setState({isFavorite: this.isCurrentPostFavorite});
  }

  get isCurrentPostFavorite() {
    let matchNumber = HotelStore.favoritesPosts.filter((el: Post) => {
      return el.translationId === this.props.sceneInfo.article.translationId;
    }).length;
    let isFavorite = matchNumber > 0;
    console.log(isFavorite);
    return isFavorite;
  }

结果组件确实挂载了log console.log('Article Scene will unmount for article: '.toUpperCase() + this.props.sceneInfo.article.name); 在更新状态之前从未显示过,在this.setState(...)之前,bool isMounted在日志中始终为true

编辑 :我知道isMounted ,这是一个反模式,我只使用它来检查日志是否安装组件,如果我删除isMounted逻辑错误仍然存​​在。

首先,您不应该检查您的组件是否已安装, 它是一个反模式

我想警告出现是因为你在componentWillUnmount中使用了setState。 我认为这个问题是setState是异步的 ,所以当你调用函数时,状态可能不会立即改变。在这种情况下,它可能会尝试在组件已经卸载时更改状态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM