簡體   English   中英

反應-警告:無法在未安裝的組件上調用setState(或forceUpdate)

[英]React - Warning: Can't call setState (or forceUpdate) on an unmounted component

我從我的應用程序中的幾個組件得到以下錯誤。

警告:無法在已卸載的組件上調用setState(或forceUpdate)。 這是空操作,但它表明應用程序中發生內存泄漏。 要解決此問題,請在componentWillUnmount方法中取消所有訂閱和異步任務。

導致此問題的組件之一在componentWillUnmount方法中具有調整大小的移除事件偵聽器。 我該如何解決此問題。 從我在在線示例中看到的情況來看,通常使用這種方法取消訂閱事件。

我不允許粘貼特定的代碼,所以我正在編寫psudo代碼

clickHandler() {
  this.setState({ opened: !(this.state.opened) });
}

componentDidMount() {
   this.setState({ width: window.innerWidth } );
   window.addEventListener('resize', this.updateWidth);
}

componentWillUnmount() {
    window.removeEventListener('resize', this.updateWidth);
}

private updateWidth() {
     if (this.state.opened &&
         window.innerWidth >= someMethodReturnsViewportConstant()) {

         this.onClickHandler();
         const htmlElement: HTMLInputElement =
             document.querySelector('#html-element-id');
         if (htmlElement && htmlElement) {
             htmlElement = false;
         }
     }
}

我做了什么:

我已經閱讀了Stack上所有與此相關的文章,但都沒有解釋為什么我的代碼導致了這個問題。

由於您沒有共享太多代碼,因此我認為以下是您正在做什么

this.updateWidth = setTimeout(() => {
   this.setState({
      width:100
   });
}, 3000);

componentWillUnmount() {
    clearTimeout(this.updateWidth);
}

因此,無論您在setTimeout中進行seState的何處,都可以像我提到的那樣在componentWillUnMount中清除它們

另外,如果您使用componentWillReceiveProps或componentDidUpdate,則需要使用nextProps或nextState檢查當前道具或狀態,如果它們不相等,則執行setState。 此檢查是強制性的。 這也是您面臨無限警告的原因

正如其他人所說,您沒有提供足夠的代碼來查看實際發生的情況。

但是,您可以做的是添加一個標志,以查看組件是否已卸載,以防止狀態更新。

這是一個例子。

class ExampleComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      exampleState: []
    };
    this.isUnmounted = false;
    this.updateState = this.updateState.bind(this);
  }

  componentWillUnmount() {
    this.isUnmounted = true;
  }

  updateState() {
    if (!this.isUnmounted) { // Don't allow state change if component is unmounted
      this.setState({ exampleState: [1, 2, 3] });
    }
  }
}

現在,您有了一個標志,可以用來調試狀態更改。 逐一檢查組件的狀態,最終您將發現警告的出處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM