2

I listen for window "scroll" events in one of my components. However when the component is unmounted, the scroll event listener is not being removed.

The following error is produced when a scroll event occurs after the component has been unmounted:

warning.js:36 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. Please check the code for the TopNavDesktop component.

How can I properly remove this event listener?

Example code:

class NavBar extends Component {
  constructor() {
    super();

    this.state = {
      distanceScrolled: null
    }
  }

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

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

  handleScroll(e){
    const distanceScrolled = e.srcElement.body.scrollTop;

    this.setState({ distanceScrolled: distanceScrolled });
  }

  render { ... } 
}

2 Answers 2

12

When you remove the listener, you're creating a new function reference.

someFn.bind(this) === someFn.bind(this) will evaluate to false.

Instead, save the function in your constructor and use that reference:

class NavBar extends Component {
  constructor() {
    super();

    this.state = {
      distanceScrolled: null
    }

    this.scrollFn = this.handleScroll.bind(this);
  }

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

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

  handleScroll(e){
    const distanceScrolled = e.srcElement.body.scrollTop;

    this.setState({ distanceScrolled: distanceScrolled });
  }

  render { ... } 
}
1
  • Wow, I'm surprised I didn't realize that someFn.bind(this) was creating a new reference. Thanks for pointing this out :)
    – Don P
    Oct 20, 2016 at 22:03
3

You should do this in this way:

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

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

By invoking second time this.handleScroll.bind(this) in componentWillUnmount you creating new function instead of passing previous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.