验证使用错误边界而不是 try/catch 来处理子组件中的错误。
¥Validates usage of Error Boundaries instead of try/catch for errors in child components.
规则详情
¥Rule Details
Try/catch 块无法捕获 React 渲染过程中发生的错误。渲染方法或钩子中抛出的错误会沿着组件树向上冒泡。只有 错误边界 可以捕获这些错误。
¥Try/catch blocks can’t catch errors that happen during React’s rendering process. Errors thrown in rendering methods or hooks bubble up through the component tree. Only Error Boundaries can catch these errors.
无效
¥Invalid
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
// ❌ Try/catch won't catch render errors
function Parent() {
try {
return <ChildComponent />; // If this throws, catch won't help
} catch (error) {
return <div>Error occurred</div>;
}
}
有效
¥Valid
此规则的正确代码示例:
¥Examples of correct code for this rule:
// ✅ Using error boundary
function Parent() {
return (
<ErrorBoundary>
<ChildComponent />
</ErrorBoundary>
);
}
故障排除
¥Troubleshooting
为什么代码检查结果告诉我不要将 use
封装在 try
/catch
中?
¥Why is the linter telling me not to wrap use
in try
/catch
?
use
钩子不会像传统意义上那样抛出错误,而是暂停组件执行。当 use
遇到待处理的 promise 时,它会暂停组件并让 React 显示回退。只有 Suspense 和 Error Boundaries 可以处理这些情况。lint 会警告 use
附近存在 try
/catch
错误,以防止混淆,因为 catch
代码块永远不会运行。
¥The use
hook doesn’t throw errors in the traditional sense, it suspends component execution. When use
encounters a pending promise, it suspends the component and lets React show a fallback. Only Suspense and Error Boundaries can handle these cases. The linter warns against try
/catch
around use
to prevent confusion as the catch
block would never run.
// ❌ Try/catch around `use` hook
function Component({promise}) {
try {
const data = use(promise); // Won't catch - `use` suspends, not throws
return <div>{data}</div>;
} catch (error) {
return <div>Failed to load</div>; // Unreachable
}
}
// ✅ Error boundary catches `use` errors
function App() {
return (
<ErrorBoundary fallback={<div>Failed to load</div>}>
<Suspense fallback={<div>Loading...</div>}>
<DataComponent promise={fetchData()} />
</Suspense>
</ErrorBoundary>
);
}