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 });
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With