javascript React Native:未处理的承诺拒绝:TypeError:未定义不是对象(评估'response.json')

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48128543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:49:26  来源:igfitidea点击:

React Native: Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'response.json')

javascriptreact-native

提问by Artyomska

When I am trying to parse the response body in a json so I can save it in a state, I receive the error from the title. For some reason, the response.json is undefined. Here is my response:

当我尝试解析 json 中的响应正文以便将其保存在某种状态时,我收到来自标题的错误。出于某种原因, response.json 是未定义的。这是我的回应:

16:28:30: Response {
16:28:30:   "_bodyInit": "\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwibmJmIjoxNTE1MjQ4OTEwLCJleHAiOjE1MTUyNTAxMTAsImlhdCI6MTUxNTI0ODkxMH0.8zIX0PjC0XHBiHTtXlDvNxbOADj2NgtxK8zC-MqxoCg\"",
16:28:30:   "_bodyText": "\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwibmJmIjoxNTE1MjQ4OTEwLCJleHAiOjE1MTUyNTAxMTAsImlhdCI6MTUxNTI0ODkxMH0.8zIX0PjC0XHBiHTtXlDvNxbOADj2NgtxK8zC-MqxoCg\"",
16:28:30:   "headers": Headers {
16:28:30:     "map": Object {
16:28:30:       "access-control-allow-credentials": Array [
16:28:30:         "true",
16:28:30:       ],
16:28:30:       "cache-control": Array [
16:28:30:         "public, max-age=0",
16:28:30:       ],
16:28:30:       "content-length": Array [
16:28:30:         "182",
16:28:30:       ],
16:28:30:       "content-type": Array [
16:28:30:         "application/json; charset=utf-8",
16:28:30:       ],
16:28:30:       "date": Array [
16:28:30:         "Sat, 06 Jan 2018 14:28:30 GMT",
16:28:30:       ],
16:28:30:       "expires": Array [
16:28:30:         "-1",
16:28:30:       ],
16:28:30:       "server": Array [
16:28:30:         "Microsoft-IIS/10.0",
16:28:30:       ],
16:28:30:       "x-aspnet-version": Array [
16:28:30:         "4.0.30319",
16:28:30:       ],
16:28:30:       "x-powered-by": Array [
16:28:30:         "ASP.NET",
16:28:30:       ],
16:28:30:     },
16:28:30:   },
16:28:30:   "ok": true,
16:28:30:   "status": 200,
16:28:30:   "statusText": undefined,
16:28:30:   "type": "default",
16:28:30:   "url": "url",
16:28:30: }

Here is the code where I receive the error:

这是我收到错误的代码:

export function loginAction(data) {
    return dispatch => Promise.all([
        dispatch(loginStarted()),
        loginService(data).then(response => {

            console.log(response);
            if (!response.ok) {
                Alert.alert('ERROR', 'User or password is incorrect');
                dispatch(loginFailed('User or password is incorrect'));
            }
            else {
                Alert.alert('OK', 'Login is a success');
            }
        }).then((response) => response.json()).then((response) => {
            console.log(response);
            dispatch(loginSuccess(response));
        })
    ]);
}

The error is received at the line where (response) => response.json() is.

在 (response) => response.json() 所在的行收到错误。

Here is the fetch request:

这是获取请求:

export const loginService = (user) => {

    return fetch(`${httpApiUrl}/api/userdata/ReactVerify`, {
        method: 'POST',
        headers: {
            'Accept': '*/*',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(user)
    })
        .then(function (response) {
            return response;
        });
};

I also tried response.text() instead of json(), but still it's undefined. How can I get the text from _bodyInit, or what am I doing wrong? Thank you.

我也试过 response.text() 而不是 json(),但它仍然是未定义的。如何从 _bodyInit 获取文本,或者我做错了什么?谢谢你。

回答by Bergi

Uh, why are you using two .thencalls? The former callback does not return anything, so the chained promise resolves with undefinedand that's exactly what the latter callback receives. Just use only one - and also don't call response.json()when the status was not ok.

呃,你为什么用两个.then电话?前一个回调不返回任何东西,所以链式承诺解决了undefined,这正是后一个回调接收的。只使用一个 - 并且response.json()在状态不好时也不要打电话。

loginService(data).then(response => {
    console.log(response);
    if (!response.ok) {
        Alert.alert('ERROR', 'User or password is incorrect');
        dispatch(loginFailed('User or password is incorrect'));
    } else {
        Alert.alert('OK', 'Login is a success');
        return response.json().then(data => {
            console.log(data);
            dispatch(loginSuccess(data));
        });
    }
})