reactjs react中的错误边界没有捕捉到子进程抛出的错误

kqlmhetl  于 2023-04-20  发布在  React
关注(0)|答案(1)|浏览(104)

我有一个ChatPage组件如下:

import React from 'react'
import axios from 'axios'
import ErrorBoundary from './ErrorBoundary'
const ChatPage = () => {
  const fetchChats= async()=>{
      const data=await axios.get('/api/getChats')
      return data
  }
  
  const [chats, setChats]=React.useState(null)
  React.useEffect(()=>{
    fetchChats().then((res)=>{
     setChats(res.data)
    })
  ;
  },[])
  return (
    <>
    <div>ChatPage</div>
    <ErrorBoundary> <div>{chats.chat}</div></ErrorBoundary>
   
    </>
  )
}

export default ChatPage

和ErrorBoundary组件如下:

import React from 'react'
class ErrorBoundary extends React.Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false };
    }
  
    static getDerivedStateFromError(error) {
      // Update state so the next render will show the fallback UI.
      return { hasError: true };
    }
  
    componentDidCatch(error, errorInfo) {
      // You can also log the error to an error reporting service
    
    }
  
    render() {
      if (this.state.hasError) {
        // You can render any custom fallback UI
        return <h1>Something went wrong.</h1>;
      }
  
      return this.props.children; 
    }
  }
  export default ErrorBoundary

但是,如果聊天状态为null,则chats.data会抛出一个错误,该错误不在错误边界中。这里可能存在什么问题?

p1iqtdky

p1iqtdky1#

实际上,ErrorBoundary捕获了一个错误,我想你认为它不工作,因为每次发生错误时,你都会看到React的覆盖。
同时拥有开发错误覆盖图和错误边界图并没有什么坏处。要查看错误边界图,您可以单击右上角的X来关闭覆盖图。

相关问题