【问题标题】:Why catch invoked with success promise?为什么使用成功承诺调用 catch?
【发布时间】:2020-05-28 08:56:50
【问题描述】:

我可能会发生奇怪的事情,我向端点“/Login”发送了一个请求,它给了我很好的响应!

我做我的事,但出于某种原因,我看到一条警告说,

未处理的 Promise Rejection / typeError: undefined is not an object (评估'error.response.data')

如果有人对此有解释?

代码sn-p

signIn = data => {
    this.setState({loading: true});
    API.post('/login', data)
      .then(response => {
        let {
          data: {
            data: {
              response: {token},
            },
          },
        } = response;
        this.setState({loading: false});
        reactotron.log('response', response);
        reactotron.log(token);
        deviceStorage.saveKey('id_token', token);
      })
      .catch(error => {
        alert('catched!!'); // it's appear :)
        this.setState({error: error.response.data, loading: false});
        reactotron.error(error.response.data);
      });
  };

= 这个函数出错了~_~!

为什么给我一个错误?

_deviceStorage.default.saveKey is not a function

import { AsyncStorage } from '@react-native-community/async-storage';
import reactotron from 'reactotron-react-native';

const deviceStorage = {
  // our AsyncStorage functions will go here :)
  saveItem= async(key, value)=>{
    try {
      await AsyncStorage.setItem(key, value);
    } catch (error) {
      reactotron.log('AsyncStorage Error: ' + error.message);
    }
  }
};

export default deviceStorage;

【问题讨论】:

  • 添加console.log(error);查看error的值。
  • @Code-Apprentice “错误:请求失败,状态码 400”!!但是当我登录error.response.data 时,我收到了我的案例错误“电子邮件/密码错误”如果数据错误

标签: javascript reactjs react-native promise axios


【解决方案1】:

error 是错误消息(拒绝消息)的字符串表示形式。但是当你说error.response.data时,你把它当作一个对象来对待

  .catch(error => {
    alert('catched!!'); // it's appear :)
    this.setState({error: error, loading: false});
    reactotron.error(error.response.data);
  });

【讨论】:

  • 好吧,但是当刚刚出现警报并删除其他行时,我可以看到它!
  • 你看到了什么?
  • 我的意思是,如果我在 catch 中保持警觉{},我会看到“catch”
  • 哦,我知道错误,它在 deviceStorage.saveKey() 中,然后 {}
【解决方案2】:

如果在 then 块中遇到错误,则可以调用 catch。检查您的 then 块是否有任何可能的错误。这可能是即使在 promise 返回成功时也会调用 catch 的原因。

const promise1 = new Promise(function(resolve, reject) {
  resolve("resp");
});

promise1.then(function(resp) {
  console.log(resp);
  throw 'error'
}).catch(function(error) {
  console.error(error);
});

【讨论】:

  • 是的,没错,然后我有一个错误,我现在看到它给出了一个错误_deviceStorage.default.saveKey is not a function
猜你喜欢
  • 1970-01-01
  • 2015-11-01
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-22
  • 1970-01-01
  • 2015-08-07
相关资源
最近更新 更多