【发布时间】:2021-01-26 19:02:18
【问题描述】:
我在index.tsx中有以下代码:
window.onerror = function(msg, url, line, col, error) {
debugger;
// Note that col & error are new to the HTML 5 spec and may not be
// supported in every browser. It worked for me in Chrome.
var extra = !col ? '' : '\ncolumn: ' + col;
extra += !error ? '' : '\nerror: ' + error;
// You can view the information in an alert to see things working like this:
alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);
// TODO: Report this error via ajax so you can keep track
// of what pages have JS issues
var suppressErrorAlert = true;
// If you return true, then error alerts (like in older versions of
// Internet Explorer) will be suppressed.
return suppressErrorAlert;
};
来源:
https://stackoverflow.com/a/10556743/3850405
如果我在另一个组件中抛出这样的错误,我会按预期捕获它:
componentDidMount() {
throw new Error();
}
如果这样抛出:
async componentDidMount() {
throw new Error();
}
错误未被捕获并显示Unhandled Rejection (Error):。
然后我尝试创建一个 React 全局错误边界。
import React, { ErrorInfo } from 'react';
interface IProps {
}
interface IState {
hasError: boolean
}
class ErrorBoundary extends React.PureComponent<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error: Error, info: ErrorInfo) {
// Display fallback UI
debugger;
console.warn(error);
console.warn(info);
this.setState({ hasError: true });
// You can also log the error to an error reporting service
//logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary
index.tsx:
<React.StrictMode>
<Provider store={store}>
<ConnectedIntlProvider>
<Router>
<ErrorBoundary>
<App />
</ErrorBoundary>
</Router>
</ConnectedIntlProvider>
</Provider>
</React.StrictMode>,
来源:
https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html
https://stackoverflow.com/a/51764435/3850405
但是效果是一样的,async componentDidMount 没有被捕获,但它按预期工作。
我发现这个帖子提到了这个问题,但没有真正的解决方案。
https://stackoverflow.com/a/56800470/3850405
如何在 React 中创建一个真正捕获所有内容的全局错误处理程序?
【问题讨论】:
-
@Pointy 是的,但我更喜欢像错误边界这样的 React 方式,但对于未处理的拒绝
-
嗯,
async和 Promise 实现是原生 JavaScript,React 无法控制它。 -
@Pointy True 但错误也是原生的,React 确实如上所示处理它们。
-
是的,但是 Promise 链中的错误由 Promise 机制处理,因为它的工作方式有可靠的行为保证——完全独立于 React。那些“未处理的拒绝”事件在内部直接发布到全局上下文(
window或 Worker 全局范围)。
标签: javascript reactjs typescript