首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >当promise中存在错误时,不会调用componentDidCatch

当promise中存在错误时,不会调用componentDidCatch
EN

Stack Overflow用户
提问于 2017-10-23 19:53:36
回答 1查看 1.8K关注 0票数 0

根据新的react 16 release doc,它说

"React 16打印在开发中呈现到控制台时发生的所有错误,即使应用程序意外地接受了这些错误。“

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

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

代码语言:javascript
复制
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'));
EN

回答 1

Stack Overflow用户

发布于 2017-10-23 20:20:48

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46888714

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档