Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.setState in setTimeout in react

Tags:

reactjs

Function to update state:

animate() {
 setInterval(function(){
   setTimeout( this.setState({
     a: '123'
   }), 1000);
 }, 4000);
}

The method called:

componentDidMount() {
  this.animate();
}

Error:

Uncaught TypeError: this.setState is not a function

Then the next code tried:

animate() {
 setInterval(function(){
   setTimeout( () => {this.setState({
     a: '123'
   })}, 1000);
 }, 4000);
}

And the next error was:

Uncaught TypeError: _this2.setState is not a function
like image 339
Polina Shchukina Avatar asked Sep 02 '25 02:09

Polina Shchukina


1 Answers

The problem stems from your definition of setInterval.

When you do setInterval(function() {...}), the this keyword is no longer bound to the React component but to the function it is called within because of the introduction of the new scope.

You can either switch it to:

animate() {
  const self = this

  setInterval(function() {
    setTimeout(() => self.setState({ a: '123' }), 1000)
  }, 4000)
}

This way self is assign to the React component value of this before the new scope is introduced, or you can use all arrow functions to preserve the this keyword referencing the component:

animate() {
  setInterval(() => {
    setTimeout(() => this.setState({ a: '123' }), 1000)
  }, 4000)
}
like image 98
m_callens Avatar answered Sep 05 '25 00:09

m_callens