取消componentWillUnmount方法中的所有订阅和异步任务

时间:2019-03-14 21:05:12

标签: javascript reactjs

有人可以让我知道componentWillUnmount我的代码所缺少的内容。

错误是

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
    in Layout (created by RoomsPage)
    in RoomsPage (created by HotExportedRoomsPage)
    in AppContainer (created by HotExportedRoomsPage)
    in HotExportedRoomsPage (created by PageRenderer)

观看次数是我们大多数人的1000倍,但我似乎无法unmount。我的问题代码是;

  componentDidMount() {
    if (typeof window !== 'undefined') {
      window.addEventListener('scroll', debounce(this.handleScroll, 32));
    }
  }

  componentWillUnmount() {
    if (typeof window !== 'undefined') {
      window.removeEventListener('scroll', debounce(this.handleScroll, 32));
    }
  }

  handleScroll = () => {
    const scrollPositionY = +window.scrollY;
    return this.setState({ scrollPositionY });
  };

2 个答案:

答案 0 :(得分:2)

您没有删除事件侦听器,因为您正在将不同的函数传递给addEventListenerremoveEventListener。这是因为具有相同定义的两个函数不相等。亲自看看:

(() => true) === (() => true) 
// false

您需要定义函数,然后将其传递。

componentDidMount() {
  window.addEventListener('scroll', this.handleScroll);
}

componentWillUnmount() {       
  window.removeEventListener('scroll', this.handleScroll);
}

handleScroll = debounce(
  () => { this.setState({ scrollPositionY: +window.scrollY }) },
  32
);

顺便说一句,在大多数情况下,您也不需要检查windowcomponentDidMount中的componentWillUnmount……SSR不会装载组件。

答案 1 :(得分:0)

您要为侦听器分配不同的实例

解决方案:

componentDidMount() {
  if (typeof window !== 'undefined') {
      this.hasScrolled = debounce(this.handleScroll, 32);
      window.addEventListener('scroll', this.hasScrolled);
  }
}

componentWillUnmount() {
  if (typeof window !== 'undefined') {
    window.removeEventListener('scroll', this.hasScrolled);
  }
}
相关问题