最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'setState') - Stack O

programmeradmin7浏览0评论

I am getting this error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'setState')

and this is my code:

class Table extends Component {
    constructor (props) {
        super(props);
        this.state = {
            employees: [],
        }
    }
    ponentDidMount() {
        this.getEmployeeList();
    }
    getEmployeeList = () => {
        axios.get("employee/list")
        .then(function(response) {

            this.setState({
                employees: response.data,
            });

        });
        console.log(this.state.employees)
    }
     
    // Remaining codes
    
}

I am getting this error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'setState')

and this is my code:

class Table extends Component {
    constructor (props) {
        super(props);
        this.state = {
            employees: [],
        }
    }
    ponentDidMount() {
        this.getEmployeeList();
    }
    getEmployeeList = () => {
        axios.get("employee/list")
        .then(function(response) {

            this.setState({
                employees: response.data,
            });

        });
        console.log(this.state.employees)
    }
     
    // Remaining codes
    
}
Share Improve this question asked Mar 26, 2022 at 10:51 Namatullah ShahbaziNamatullah Shahbazi 2381 gold badge9 silver badges22 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

Here you are passing an anonymous function to the axios.then callback.

axios.get("employee/list")
.then(function(response) {

    this.setState({
        employees: response.data,
    });

});

This function has it's own this that has no setState property on it. To solve this issue, you have to either bind this like so:

axios.then(
  function (response) {
    this.setState({
      employees: response.data
    });
  }.bind(this)
);

Or use an arrow function, which will bind the outer this automatically

axios.then(
 (response) =>{

    this.setState({
      employees: response.data
    });
  }
);

This is because the callback you pass in is a function expression, which has its own this binding.

To solve this error you can:

  1. Use arrow functions:
getEmployeeList = () => {
  axios
    .get("employee/list")
    .then((response) => {
      this.setState({
        employees: response.data,
      });
    });
};
  1. Save this to self variable, and call it instead:
getEmployeeList = () => {
  const self = this;
  axios
    .get("employee/list")
    .then(function (response) {
      self.setState({
        employees: response.data,
      });
    });
};

kindly recheck your spelling. Most typeError issues are due to spelling mistakes

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论