reactjs / reactjs/react.dev

Unexpected warning for error boundaries without getDerivedStateFromError

未关闭
#3,028 6 条评论 4 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
JavaScript
星标
11.8k
派生
7.9k
平均合并
1 天 11 小时
30 天内合并 PR
11

描述

(Note: I dismissed the idea described here by now, but I still felt like reporting my findings.)

Steps to reproduce

I create a reusable error boundary component, ErrorCatcher, in order to deduplicate across different error boundary components.

class ErrorCatcher extends React.Component {
  componentDidCatch(error, info) {
    this.props.onError(error);
  }

  render() {
    return this.props.children;
  }
}

I then create new error boundary on top of that. For example:

function ErrorBoundary({children}) {
  const [error, setError] = useState(null)

  if (error) {
    return <ErrorMessage error={error} />
  }

  return (
    <ErrorCatcher
      onError={error => setError(error)}}
    >
      {children}
    </ErrorCatcher>
  )
}

For convenience, check out this Codesandbox for a live example.

Actual Behavior

Testing it out, I notice that React prints the following warning to the console:

Warning: ErrorCatcher: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI.

Expected Behavior

Checking the documentation, I find the following (emphasis mine):

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods [...]

That leaves me a bit puzzled, since on the one hand the documentation is offering me to define either, and on the other I get a warning. I want the documentation to be explicit about eventual error and warning messages.

If you see some value in enabling users to create ErrorCatcher, without being bugged by the warning, I could see other solutions: get rid of the message, or make it optional.

Kindest regards 🙃

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

该 issue 提到了 error-boundary 文档和一个 Codesandbox 复现,但没有提到任何 repository 文件或测试。先检查 componentDidCatch、getDerivedStateFromError 与针对该复现的警告之间在文档中所述的关系;当文档明确符合观察到的行为时即完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
react
领域
documentation
Issue 类型
文档
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
基本清楚
新手友好度
28/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。