React js错误边界不适用于Promise Catch

时间:2018-09-15 16:11:24

标签: reactjs react-native error-handling react-redux react-router

我们有一个错误边界组件:

import React from 'react';
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorMessage:''};
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true, errorMessage: error });
    // You can also log the error to an error reporting service
  }

  render() {
    if (this.state.hasError) {
      debugger
      // You can render any custom fallback UI  
      return <h1>{this.state.errorMessage.toString()}</h1>;
    }
    return this.props.children;
  }
}

export default ErrorBoundary;

我们正像这样使用它:

ReactDOM.render(
    <Provider store={store}>
        <Router>
            <CookiesProvider>
                <ErrorBoundary>
                    <NetworkMgmt />
                </ErrorBoundary>
            </CookiesProvider>
        </Router>
    </Provider>,
     document.getElementById('root')
);

此后,我尝试使用下面的代码片段引发错误,但这并不调用错误边界componentDidCatch(),而是引发未处理的异常。

    dataService.getNetworkSummary().then(function (result) {
        debugger
        self.networks = result;
        self.setState({
            items: result.slice(0, 20),
            total: result.length,
            skip: 0,
            pageSize: 20,
            pageable: {
                buttonCount: 5,
                info: true,
                type: 'numeric',
                pageSizes: [20, 40, 60, 80, 100],
                previousNext: true
            },
            sortable:{
                allowUnsort: true,
                mode: 'single',
                sortDir:'Asc'
            }

        })
    }).catch(err =>
         {
             throw new Error("This is my error");
         });

有什么办法可以正确地做到这一点。

1 个答案:

答案 0 :(得分:0)

就像在承诺中一样,您正在捕获错误,这意味着它不会在组件中显示错误,因为您已经处理了函数中的错误。 catch的目的是处理该块中的错误而不干扰组件。如果您想手动引发错误,可以使用

throw 'Some Error';

或者您可以删除不建议使用的挡块。

更新:错误边界会在渲染期间,生命周期方法以及它们下面的整个树的构造函数中捕获错误。