首页 > 解决方案 > 是什么导致未处理的承诺拒绝:未定义不是对象(评估'_context.t0.response.data')?

问题描述

我不断收到 Unhandled Promise Rejection: TypeError: undefined is not an object(评估 '_context.t0.response.data')。在进行了一些挖掘之后,我的错误似乎来自我的这部分代码。正是 authUser 函数似乎导致了问题

import { addError, removeError } from './error';
import { SET_CURRENT_USER } from '../actionTypes';
import api from '../../services/api';

export const setCurrentUser = user => ({
    type: SET_CURRENT_USER,
    user
});

export const setToken = token => {
    api.setToken(token);
};

export const authUser = (path, data) =>
{
    return async dispatch => {
        try {
            const {token, ...user} = await api.call('post', `auth/${path}`, data);
            AsyncStorage.setItem('jwtToken', token);
            api.setToken(token);
            dispatch(setCurrentUser(user));
            dispatch(removeError());
        } catch (err) {
            const error = err.response.data;
            dispatch(addError(error.message));
        }
    }
};

actionTypes.js

export const SET_CURRENT_USER = 'SET_CURRENT_USER'

api.js

import axios from 'axios';

const host = 'http://localhost:4000/api';

export const setToken = token => {
    if (token) {
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    } else {
        delete axios.defaults.headers.common['Authorization'];
    }
};

export const call = async (method, path, data) => {
    const response = await axios[method](`${host}/${path}`, data);
    return response.data;
};

export default { setToken, call };

错误.js

import {ADD_ERROR, REMOVE_ERROR} from '../actionTypes';

export const addError = error => ({
    type: ADD_ERROR,
    error
});

export const removeError = () => ({
    type: REMOVE_ERROR
});

错误:

Possible Unhandled Promise Rejection (id: 4):
TypeError: undefined is not an object (evaluating '_context.t0.response.data')
_callee$@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:107239:43
tryCatch@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:26927:23
invoke@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27103:32
tryCatch@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:26927:23
invoke@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27003:30
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27015:21
tryCallOne@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:28865:16
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:28966:27
_callTimer@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:32405:17
_callImmediatesPass@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:32441:19
callImmediates@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:32659:33
callImmediates@[native code]
__callImmediates@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2719:35
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2505:34
__guard@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2702:15
flushedQueue@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2504:21
flushedQueue@[native code]
callFunctionReturnFlushedQueue@[native code]

此外,如果它有帮助,我遵循了 localhost 链接和在那里中断的功能,但我没有写这个并且无法更改它。


  var authUser = function authUser(path, data) {
    return function _callee(dispatch) {
      var _await$api$call, token, user, error;

      return _regenerator.default.async(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return _regenerator.default.awrap(_api.default.call('post', "auth/" + path, data));

            case 3:
              _await$api$call = _context.sent;
              token = _await$api$call.token;
              user = (0, _objectWithoutProperties2.default)(_await$api$call, ["token"]);
              AsyncStorage.setItem('jwtToken', token);

              _api.default.setToken(token);

              dispatch(setCurrentUser(user));
              dispatch((0, _error.removeError)());
              _context.next = 16;
              break;

            case 12:
              _context.prev = 12;
              _context.t0 = _context["catch"](0);
              error = _context.t0.response.data;
              dispatch((0, _error.addError)(error.message));

            case 16:
            case "end":
              return _context.stop();
          }
        }
      }, null, null, [[0, 12]], Promise);
    };
  };

标签: node.jsreact-nativeexpress

解决方案


错误来自authUser函数的 catch 块:

export const authUser = (path, data) =>
{
    return async dispatch => {
        try {
           // ... Other existing codes
        } catch (err) {
            const error = err.response.data;
            dispatch(addError(error.message));
        }
    }
};

对于 axios 抛出的错误,err.response并不总是可用,有时当服务器没有响应或首先发出请求时出现问题,err.response将是undefined. 在这种情况下,您需要处理其他错误来源。您应该更新 catch 逻辑来处理可能的错误情况,代码应该是这样的:

catch (err) {
    if (error.response) {
        // There is an error response from the server
        // You can anticipate error.response.data here
        const error = err.response.data;
        dispatch(addError(error.message));
    } else if (error.request) {
        // The request was made but no response was received
        // Error details are stored in error.reqeust
        console.log(error.request);
    } else {
        // Some other errors
        console.log('Error', error.message);
    }
}

有关处理 axios 错误的更多详细信息,请点击此处


推荐阅读