React state update on an unmounted componentというエラーが出た時のメモ

出たエラー

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

何していたか

react-router-domreact-routerwithRouterを使って、this.props.history.push(URL)で画面遷移しようとしたら起こった。

解決策

↑のコードでURLを変更して次の画面に行くはずが、↓のコードでURLを変更していたのが原因だったみたいです。

↑これは、stateってやつを更新しちゃうので良くなかったみたい。

参考にしたサイト

ReactでCan’t perform a React state update on an unmounted component.の原因と解決

React Can’t perform a React state update on an unmounted component. が出た時に確認すること

と思ったらまた出た…

この関数が実行されているとエラーになるみたい。
修正してみました↓。

ちょっと分かり難いですが、、、。
constructorthis.mounted = false;を足して、
this.mounted && this.setState(//ほにゃらら)としています。
removeEventListenerも追加しています。

参考にしたサイト

React コンポーネントのアンマウント時のエラーを修正する方法(componentWillUnmount)

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です