reactjs / reactjs/react.dev

Unexpected warning for error boundaries without getDerivedStateFromError

オープン
#3,028 コメント 6 件 リアクション 4 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
JavaScript
スター
11.8k
フォーク
7.9k
平均マージ
1日 11時間
マージ済み PR(30日)
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. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

issue では error-boundary のドキュメントと Codesandbox の再現手順が示されていますが、リポジトリのファイルやテストは示されていません。まず、componentDidCatch、getDerivedStateFromError、再現手順に対する警告の間にある、ドキュメント化された関係を確認してください。ドキュメントが観測された動作と明示的に一致すれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
react
領域
documentation
issue の種類
ドキュメント
難易度
2/5
見積もり時間
1〜3時間
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
28/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。