Javascript 如果在传递给setTimeout的函数中出现错误,那么组件不会崩溃,原因是什么? 类计数器扩展React.Component{ 建造师(道具){ 超级(道具); this.state={counter:0}; } handleClick=()=>{ this.setState(({counter})=>({ 柜台:柜台+1 })); }; simError=()=>{ x/2; }; render(){ if(this.state.counter==5){ //未定义模拟JS错误x //这将使组件'this.simErro()崩溃` //this.simError() //但这不会`setTimeout(this.simError,0)` //setTimeout(this.simError,0); } 返回{this.state.counter}; } }
如果取消注释setTimeout(this.simError,0);组件不会崩溃,但您会在控制台中看到错误。Javascript 如果在传递给setTimeout的函数中出现错误,那么组件不会崩溃,原因是什么? 类计数器扩展React.Component{ 建造师(道具){ 超级(道具); this.state={counter:0}; } handleClick=()=>{ this.setState(({counter})=>({ 柜台:柜台+1 })); }; simError=()=>{ x/2; }; render(){ if(this.state.counter==5){ //未定义模拟JS错误x //这将使组件'this.simErro()崩溃` //this.simError() //但这不会`setTimeout(this.simError,0)` //setTimeout(this.simError,0); } 返回{this.state.counter}; } },javascript,reactjs,Javascript,Reactjs,如果取消注释setTimeout(this.simError,0);组件不会崩溃,但您会在控制台中看到错误。 链接到免责声明:我不是React开发人员,因此我的答案与此代码的React组件部分无关 异步抛出的异常(例如在超时中)不会影响以前的代码同步执行,因为该代码早在超时触发之前就已完成 考虑: 函数helloWorld(){ console.log(“你好”); 试一试{ setTimeout(函数(){ 抛出新错误(“Oops!”); },100); } 捕捉(错误){ log(“从未到过
链接到免责声明:我不是React开发人员,因此我的答案与此代码的React组件部分无关 异步抛出的异常(例如在超时中)不会影响以前的代码同步执行,因为该代码早在超时触发之前就已完成 考虑: 函数helloWorld(){ console.log(“你好”); 试一试{ setTimeout(函数(){ 抛出新错误(“Oops!”); },100); } 捕捉(错误){ log(“从未到过这里”); } console.log(“世界”); } helloWorld(); 这个程序将打印“Hello”,然后打印“World”,100毫秒后将抛出异常“Oops!”。但由于它是异步发生的,
helloWorld()
早就完成了,这意味着它不可能知道发生了异常。它当然不可能阻止《世界》的印刷,因为这个例外还没有发生
由于同样的原因,try..catch
也不会捕获异常。这将是一个未处理的异常,JS环境将全局捕获并转储到控制台
旁注:如果要捕获全局未处理的异常,您有一些选项。在浏览器中,可以设置窗口。错误处理程序。在节点中,为uncaughtException
事件在process
上设置侦听器。感谢您的解释:)首先:try…catch
未捕获错误,因为部分代码是同步的,并且在错误发生之前已经完成。这是否意味着try..catch
只能获取同步错误?第二:在上面的例子中,我知道错误发生在超时之后,但事件侦听器如何在超时之后继续工作?我很清楚,在你们的例子中,函数代码是完成的,函数是完成的,然后错误就发生了。但在上面的代码中,即使在发生错误后,事件侦听器仍能继续工作。这是针对React的,还是也适用于Vanilla JS?
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>;
}
}