[React]this.setState is not a functionの解決法

  • 2021年3月13日
  • 2021年7月5日
  • React
  • 171view

エラー内容

該当箇所のコード

エラーコードを読む

this.setStateが関数じゃないと言っている。

callback内のthisの挙動

どうやらthisが悪さをしてsetStateが動作していないらしい。
callback関数内のthisはグローバルのwindowオブジェクトを示してしまう

解決策① arrow関数

arrow関数を使って表記すればthisの挙動が正しくなる。

解決策② .bind

.bindを使うことでthisの挙動を正しく出来るらしい。
自分は①のやり方で解決したので、参考サイトだけ貼っておく。

https://stackoverflow.com/questions/31045716/react-this-setstate-is-not-a-function

Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
  • Attributes
  • Custom attributes
  • Custom fields
Click outside to hide the compare bar
Compare
Compare ×
Let's Compare! Continue shopping