当 Promise 出现错误时,不会调用 componentDidCatch

Joh*_*ohn 0 reactjs react-fiber

根据新的React 16 发布文档,它说

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

我有一个组件和一个组件。我在 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'));
Run Code Online (Sandbox Code Playgroud)

Ken*_*ong 6

只是想向任何进入这个问题寻求答案的人指出。

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

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

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