Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel all subscriptions and asynchronous tasks in the componentWillUnmount method

Can someone let me know what I am missing to componentWillUnmount my code.

The Error is

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)

Seen it a thousand times as most of us have but I don't appear to be able to unmount. My code in question is;

  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 });
  };
like image 551
Darren Avatar asked Dec 20 '25 21:12

Darren


1 Answers

You're not removing the event listener because the you're passing different functions to addEventListener and removeEventListener. This is because two functions with identical definitions are not equal. See for yourself:

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

You need to define your function, then pass it.

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

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

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

By the way, you also don't need to check for window in componentDidMount or componentWillUnmount in most circumstances… SSR doesn't mount components.

like image 148
coreyward Avatar answered Dec 23 '25 11:12

coreyward