简体   繁体   中英

'undefined is not an object' error when using this.setState within a setTimeout function

I am using a setTimeout function which runs on a loop alternating between a boolean state using setState . However when this.setState gets called in the function I receive the following error:

TypeError: undefined is not an object (evaluating: 'this.state.percentages')

Below is a snippet of the code I am using - I would be very grateful to anyone who can point out the mistake I am making:


constructor(props) {
    super(props);
    this.state = {
      percentages: false,
    };
  }      

loopPercentages() {
    setTimeout(function() {
      this.setState({ percentages: !this.state.percentages });
        loopPercentages();
    }, 10000);
}
    
componentDidMount() {
  this.loopPercentages();
}

import React from "react";

export class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      percentages: false
    };
  }

  loopPercentages = () => {
    setTimeout(() => {
      this.setState({ percentages: !this.state.percentages });
      this.loopPercentages();
    }, 10000);
  };

  componentDidMount() {
    this.loopPercentages();
  }

  render() {
    return (
      <div>
        <h1>Hello StackOverflow</h1>
      </div>
    );
  }
}

Use the setState callback function to get always the current state value:

loopPercentages() {
    setTimeout(() =>  { //--> this component scope
      this.setState((prev) => ({ percentages: !prev.percentages }));
      this.loopPercentages();
    }, 10000);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM