如果您在传递给setTimeout的函数中遇到错误,那么组件不会崩溃,为什么


class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
}
handleClick = () => {
this.setState(({ counter }) => ({
counter: counter + 1
}));
};
simError = () => {
x / 2;
};
render() {
if (this.state.counter === 5) {
// Simulate a JS error x is not defined
// this will crash the component `this.simErro()`
//this.simError()
// but this will not `setTimeout(this.simError, 0);`
//setTimeout(this.simError, 0);
}
return <h1 onClick={this.handleClick}>{this.state.counter}</h1>;
}
} 

如果取消注释setTimeout(this.simError,0);组件不会崩溃,但您会在控制台中看到错误。链接到代码笔

免责声明:我不是React开发人员,所以我的答案与此代码的React组件部分无关。

异步抛出的异常(如超时)不会影响代码的上一次同步执行,因为该代码早在超时触发之前就已经完成了。

考虑:

function helloWorld() {
console.log("Hello");
try {
setTimeout(function(){
throw new Error("Oops!");
},100);
}
catch (err) {
console.log("Never got here.");
}
console.log("World");
}
helloWorld();

这个程序将打印"你好",然后是"世界",然后100毫秒后会抛出一个异常"哎呀!"。但由于它是异步发生的,helloWorld()早就完成了,这意味着它不可能知道发生了异常。它当然无法阻止《世界》的印刷,因为这个例外还没有发生。

出于同样的原因,try..catch也不会捕获异常。它将是一个未处理的异常,并将被JS环境全局捕获并转储到控制台。

附带说明:如果您想捕获全局未处理的异常,您可以选择一些选项。在浏览器中,您可以设置window.error处理程序。在Node中,为uncaughtException事件在process上设置一个侦听器。

最新更新