簡體   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