Javascript Fetch API方法中的React本机捕获无效

Javascript Fetch API方法中的React本机捕获无效,javascript,json,react-native,Javascript,Json,React Native,我正在尝试从API获取一些数据并在我的应用程序上显示。所以为了处理错误和获取数据,我使用了下面的代码 async componentDidMount() { let data = await fetch('https://demo61235421.mockable.io/getDfo') .then((response) => response.json()) .then((responseJson) => { this.setState({ totOrder : re

我正在尝试从API获取一些数据并在我的应用程序上显示。所以为了处理错误和获取数据,我使用了下面的代码

async componentDidMount() {
let data =  await fetch('https://demo61235421.mockable.io/getDfo')
.then((response) => response.json())
.then((responseJson) => {
  this.setState({
    totOrder : responseJson.totalOrders,
  })
})
.catch((error) => {
  console.error('error')
});
return data;
}
但当我从API得到错误响应时,这段代码不会在模拟器屏幕上显示错误。我不知道为什么,但屏幕保持不变

这是我的JSON响应

{
   "error": "Error 445"
}
问题

  • 为什么这没有捕捉到错误?我错过了什么
  • 正如我所知,由于JSON响应包含名为“error”的ID,因此应该 我在工作。我说得对吗
  • 更新

    将代码更改为“以下”后,仍然不会显示错误

    async componentDidMount()
    {
      try
      {
        let data =  await fetch('https://demo64533421.mockable.io/getDfo');
        let responseJson = await data.json();
        this.setState({
          Data : true,
          totOrder : responseJson.totalOrders,
        })
      }
      catch(error) 
      {
        console.error(error)
      }
    
    }
    

    此外,响应状态已设置为
    500(内部服务器错误)
    code。

    您使用的是异步/等待。你不需要“then”和“catch”。使用回调函数(then/catch)的目的是用于异步行为,其中“fetch”是异步的。但是,当您说“wait”时,它正在等待从获取中返回结果

    你应该这样做:

    async componentDidMount() {
       try {
          let data =  await fetch('https://demo61235421.mockable.io/getDfo')
          // Do success scenarios here.
       }catch(err){
          // Perform error handling here
       }
    }
    

    对于fetch API,服务器返回的状态也很重要,根据我的经验,如果不是基于HTTP的错误状态代码(例如404500),则可能不会抛出错误。

    数据中返回了什么?我想知道您观察到的问题是否与React Native有关。具体来说,
    console.error
    会在用户界面中显示红色的大警告,这使应用程序看起来像是崩溃了。它确实捕捉到了错误。请改为尝试
    console.log
    console.debug
    ,这将在开发人员控制台上显示错误,使视图保持不变。