【问题标题】:componentDidCatch is not getting called when there is an error in promise当 promise 出错时不会调用 componentDidCatch
【发布时间】:2018-04-03 23:07:29
【问题描述】:

根据新的react 16 release doc 它说

“React 16 将渲染过程中发生的所有错误打印到开发中的控制台,即使应用程序不小心吞下了它们。”

我有一个 Parent 组件和一个 Child 组件。我在 then 承诺块中触发了一个错误。但它会调用 promise 的 catch 方法,不会调用父组件的 componentDidCatch。我不确定这是否是预期的行为。

这里是 jsfiddle https://jsfiddle.net/john1jan/Luktwrdm/14/

class Parent extends React.Component {  
  constructor(props){
    super(props);
    this.state={hasError:false}
  }

  render() {
    if(this.state.hasError){
      return <div>Something went wrong</div>
    }

    return (
      <div>
        <h1>I am parent</h1>
        <Child></Child>
      </div>
    );
  }
  componentDidCatch(error,errorInfo){
    this.setState({
      hasError:true
    })
  }
}

class Child extends React.Component {

  render() {
    return (
      <div>
        <h1>I am child</h1>
      </div>
    );
  }

  componentDidMount(){
    fetch("https://jsonplaceholder.typicode.com/posts").then((response) => {
      throw new Error("I am the error in promise");
    }).catch((error)=>{
      console.log("Error caught in catch",error);
    })
    ;
  }
}

ReactDOM.render(<Parent name="world"/>, 
document.getElementById('container'));

【问题讨论】:

  • 因为错误不在组件中,所以没有什么可捕获的。实际上,您已经自己捕获了异常并选择将其记录到控制台。如果你想传递它,只需在你的 catch 中重新抛出错误。
  • 错误是在组件生命周期方法中吧?
  • 文档中的更多内容说“React 16 会打印在开发中渲染到控制台期间发生的所有错误,即使应用程序不小心吞下了它们。”。如果之后我忘记添加 catch 块怎么办?
  • 一旦你发现一个错误,这个错误就被认为已经被处理,因此不再有错误了。

标签: reactjs react-fiber


【解决方案1】:

您正在捕获错误,并且 catch 的返回是一个承诺,因此您不再有错误,如果您在 componentDidMount 中删除 .catch ,这应该可以工作!

【讨论】:

    【解决方案2】:

    只是想向任何遇到此问题并寻求答案的人指出。

    React 16 将在渲染期间发生的所有错误打印到开发中的控制台,即使应用程序不小心吞下了它们。

    componentDidCatch 只会在渲染生命周期方法中触发。

    因为您的错误是在 promise 中抛出的。它是异步,不会成为渲染生命周期的一部分,因此您需要自己处理错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      • 2018-05-09
      • 2018-08-02
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多