javascript - 如果传递给 setTimeout 的函数出现错误,组件不会崩溃,为什么?

标签 javascript reactjs

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);该组件不会崩溃,但您会在控制台中看到错误。 链接至codepen

最佳答案

免责声明:我不是 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();

该程序将打印“Hello”,然后打印“World”,然后 100 毫秒后打印异常“Oops!”将被抛出。但由于它是异步发生的,helloWorld() 早已完成,这意味着它不可能知道发生了异常。它当然不可能阻止“World”被打印,因为异常还没有发生。

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

旁注:如果您想捕获全局未处理的异常,您有一些选择。在浏览器中,您可以设置 window.error 处理程序。在 Node 中,在 process 上为 uncaughtException 事件设置监听器。

关于javascript - 如果传递给 setTimeout 的函数出现错误,组件不会崩溃,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54215970/

相关文章:

javascript - 用于查找链接的正则表达式

javascript - 为什么现在命令行的每个参数后面都有两个连字符 (--)?它起源于何处,为什么不使用单个连字符?

php - 制作实时时钟javascript

javascript - 特定子项的特定数组 Prop [React]

javascript - 在函数react中传递默认参数值

reactjs - 使用 header 通过 fetch-mock 模拟获取请求

javascript - 通缉 : Minimal cross-browser Javascript library

javascript - 如何在 react 中动态获取宽度?

reactjs - 如何使用钩子(Hook)通过现有的 redux 操作获取数据?

javascript - 为什么 javascript 不能替换 Chrome 或 IE 中的全局标志,我该如何解决?