错误边界
Catching 渲染错误使用错误边界 and showing fallback UI gracefully.
你将学到
- 什么错误边界是 and 为什么它们是 需要
- 创建错误边界类 组件
- Showing fallback UI and logging 错误
- Limitations 的错误边界
概念讲解
The Problem Error Boundaries Solve
React components can throw errors during rendering, in lifecycle methods, or in constructors. Before error boundaries, an error in any component would unmount the entire React tree, showing a blank screen. This is a terrible user experience — one broken widget takes down the whole page. Error boundaries are React components that catch these errors anywhere in their child component tree, log them, and display a fallback UI instead of crashing the whole app.
Creating an Error Boundary
Error boundaries are currently class components only — there is no hook equivalent yet. A class component becomes an error boundary by implementing either getDerivedStateFromError() (to update state when an error is caught) or componentDidCatch() (to log the error). The getDerivedStateFromError method receives the error and returns a state update to trigger the fallback render. The componentDidCatch method receives the error and an info object with the component stack, useful for logging.
Using Error Boundaries
Wrap any part of your component tree in an error boundary. You can have multiple boundaries at different levels — a boundary around a specific widget isolates its errors from the rest of the page. The boundary's fallback UI can be anything: an error message, a retry button, or a skeleton placeholder. When the error is caught, only the subtree inside the boundary is replaced with the fallback; the rest of the app continues working.
Limitations
Error boundaries do not catch errors in event handlers, async code (setTimeout, requestAnimationFrame), or server-side rendering. For those, use try/catch blocks. Error boundaries only catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. Also, an error boundary cannot catch errors thrown by itself — only by its children.
Resetting Error State
Once an error boundary catches an error, it stays in the error state until the boundary re-renders. To reset it, you can change a 键 prop on the boundary (forcing a remount), provide a retry button that clears the error state, or use a route change to remount the boundary. This is important for user experience — users should be able to recover from errors without refreshing the page.
示例代码
import React from "react";
// Error boundary — must be a class component.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
// Update state so the next render shows fallback UI.
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
// Log the error to an error reporting service.
componentDidCatch(error, errorInfo) {
console.error("Caught error:", error, errorInfo);
// logErrorToService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return (
<div className="error-fallback">
<h2>Something went wrong.</h2>
<p>{this.state.error?.message}</p>
<button onClick={() => this.setState({ hasError: false })}>
Try Again
</button>
</div>
);
}
return this.props.children;
}
}
// Usage — wrap any component to isolate its errors.
function App() {
return (
<ErrorBoundary>
<Header />
<ErrorBoundary>
<WidgetThatMightCrash />
</ErrorBoundary>
<Footer />
</ErrorBoundary>
);
}
ErrorBoundary catches 错误 in 它的 children, shows fallback 使用 retry button, and logs 错误. 多个边界 isolate 不同部分的 UI.
动手试一试
- Code Diff
Compare 错误 handling 方法当 添加边界.
- JSON Formatter
格式错误 stack traces and 组件信息 for logging.
常见错误
错误写法
Expecting 错误边界到 catch 事件处理函数错误
正确做法
错误边界仅 catch 错误期间渲染, lifecycle 方法, and constructors. For 事件处理函数 and 异步 code, use try/catch. 这个是 React limitation, 不 bug.
错误写法
不 providing meaningful fallback UI
正确做法
空白 fallback 是 as 坏 as crash. Show helpful 消息, retry button, or contact 信息. Let 用户 know 什么 happened and 什么它们能 做关于它.
练习 错误边界
4 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。