3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React の ErrorBoundary で非同期のエラーをキャッチする

Posted at

React の ErrorBoundary は、ドキュメントにあるように非同期のエラーをキャッチできない。

async function getUser() {
  /* ... */
}
function Profile() {
  const [user, setUser] = useState(null);
  useEffect(() => {
    (async () => {
      try {
        const user = await getUser();
      } catch (error) {
        // このエラーは ErrorBoundary でキャッチできない
        throw error;
      }
      setUser();
    })();
  }, []);

  if (!user) return null;
  return <div>{user.name}</div>;
}
function App() {
  return (
    <ErrorBoundary>
      <Profile />
    </ErrorBoundary>
  );
}

Dan Abramov 曰く、こういうテクニックで想定どおりのキャッチができる。

const [, setState] = useState();
setState(() => { new Error("Hi") });

なので、さっきのコードでいうと

async function getUser() {
  /* ... */
}
function Profile() {
  const [user, setUser] = useState(null);
  const [, setState] = useState();
  useEffect(() => {
    (async () => {
      try {
        const user = await getUser();
      } catch (error) {
        // これは ErrorBoundary でキャッチできる
        setState(() => {
          throw error;
        });
      }
      setUser();
    })();
  }, []);

  if (!user) return null;
  return <div>{user.name}</div>;
}
function App() {
  return (
    <ErrorBoundary>
      <Profile />
    </ErrorBoundary>
  );
}

こうすれば ErrorBoundary でキャッチできる

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?