LoginSignup
0
0

More than 3 years have passed since last update.

【React】 マウントされていない状態でsetState()を実行した際に発生するエラーを解消する

Posted at

はじめに

reactでコンポーネントがマウントされたときに、setStateを呼び出しstateを定義する実装をしているときに、

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the ComponentA component.

というエラーで詰まったので、解決したときのメモ。

内容

結論

エラー文に書いてある通りで、マウントされていないコンポーネントでsetState()を呼んでいることがダメです。

以下のように、refを使って要素がしっかり更新されたときにsetState()を実行するようにします。

class ComponentA extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {}
        };
    }
    componentDidMount() {
        this.hogeHoge();
    }
    hogeHoge() {

        // 以前の処理(あれば)

        // ここでdivに付与された「ref="myRef"」が存在するかどうかを確認
        if (this.refs.myRef) {
            this.setState({
                data: hogehoge // hogehogeは、以前の処理で処理された変数とか
            });
        }

        // 以降の処理(あれば)
    }
    render() {
        return (

            <div className="hoge" ref="myRef">
            </div>
        );
    }
}

追加したのは、

- setStateを実行する前の条件分(if(this.refs.myRef))
- divのref(ref="myRef")

です。

詳細

はじめは、componentDidMount()時に実行しているのに、なぜ

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the ComponentA component.

とエラーが出て、コンポーネントマウントされる前に実行していると出るんだろうと思っていましたが、、、
omponentDidMount()のせいで、stateが変更されてもう一度render()が実行されるからなのか・・・?
よくわからんという状態でした。。。

詳しい理由をご存じの方、ご教示いただければ幸いです。

ひとまず、refsを使ってしっかりマウントされた後をチェックすればエラーを吐かなくなるからいいかと・・・

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0