React.js エラー「× Unhandled Rejection (TypeError): Cannot read property ‘setState’ of undefined」が発生した際の対処法

React.js エラー「× Unhandled Rejection (TypeError): Cannot read property ‘setState’ of undefined」が発生した際の対処法

axiosでpostしたresponseをthis.setStateしようとした際に「State× Unhandled Rejection (TypeError): Cannot read property ‘setState’ of undefined」が発生したので、対応方法を記述してます。

環境

  • OS  CentOS Linux release 8.0.1905 (Core)
  • node V13.11.0
  • npm 6.14.3
  • React 16.13.0

react.js環境構築

create-react-appで構築してます。

エラー全文

Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined

対応方法

アロー関数に変更すれば、エラーはなくなります。

下記のコードを

then(function (response) {
      console.log(response.data.token);
      const data = response.data.token; 
      this.setState({
        token: data
      });

下記のようにアロー関数に変更します。

.then(response => {
      console.log(response.data.token);
      const data = response.data.token; 
      this.setState({
        token: data
      });