admin管理员组文章数量:1325332
I need a setState inside a timeout in my ponent, so I've done this:
ponentDidMount() {
this.timeouts.push(setTimeout(() => {
this.setState({ text: 2 });
}, 4000));
}
ponentWillUnmount() {
this.timeouts = [];
}
But I'm getting this error:
Warning: setState(...): Can only update a mounted or mounting ponent.
This usually means you called setState() on an unmounted ponent.
This is a no-op.
What am I doing wrong?
I need a setState inside a timeout in my ponent, so I've done this:
ponentDidMount() {
this.timeouts.push(setTimeout(() => {
this.setState({ text: 2 });
}, 4000));
}
ponentWillUnmount() {
this.timeouts = [];
}
But I'm getting this error:
Warning: setState(...): Can only update a mounted or mounting ponent.
This usually means you called setState() on an unmounted ponent.
This is a no-op.
What am I doing wrong?
Share Improve this question edited Mar 2, 2017 at 14:25 Matheus Lima asked Mar 2, 2017 at 14:07 Matheus LimaMatheus Lima 2,1433 gold badges33 silver badges49 bronze badges 13- Before you call setState your ponent will be mounted but your ponent is not mounted – Ihor Skliar Commented Mar 2, 2017 at 14:11
- 1 @MatheusLima when your setState was called, your ponent is unmounted, don't forget you are using timeout! – Ihor Skliar Commented Mar 2, 2017 at 14:15
- 1 Does your ponent unmount within that 4 second frame? – Nick Zuber Commented Mar 2, 2017 at 14:19
- 1 @NickZuber I think that this is it! I'm probably not unmounting it properly. I'll update the question. – Matheus Lima Commented Mar 2, 2017 at 14:23
- 1 You should be clearing the timeouts when you unmount the ponent, and I think @IhorSkliar is right – Shubham Khatri Commented Mar 2, 2017 at 14:24
1 Answer
Reset to default 7Change your ponentWillUnmount
to clear the timeouts properly. You need to make use of clearTimeout
to clear the timeout instead of emptying the array.
ponentDidMount() {
this.timeouts.push(setTimeout(() => {
this.setState({ text: 2 });
}, 4000));
}
clearTimeouts: function() {
this.timeouts.forEach(clearTimeout);
}
ponentWillUnmount() {
this.clearTimeouts();
}
本文标签: javascriptReact setState can only update a mounted or mounting componentStack Overflow
版权声明:本文标题:javascript - React: setState can only update a mounted or mounting component - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742196535a2431185.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论