簡體   English   中英

可能未處理的 Promise 拒絕 - React-Native with Firebase

[英]Possible Unhandled Promise Rejection - React-Native with Firebase

我正在嘗試使用 React-Native 應用程序對新的 Firebase 實例進行 fetch API 調用,但我遇到了以下錯誤:

Possible Unhandled Promise Rejection (id: 0):
Network request failed
TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:25119:8)
    at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:10405:15)
    at XMLHttpRequest.setReadyState (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:26688:6)
    at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:26536:6)
    at http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:26630:52
    at RCTDeviceEventEmitter.emit (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:9638:23)
    at MessageQueue.__callFunction (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:7493:34)
    at http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:7375:8
    at guard (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:7306:1)
    at MessageQueue.callFunctionReturnFlushedQueue (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&minify=false:7374:1)

函數看起來像這樣:

 getNotes(username){
    username = username.toLowerCase().trim();
    var url = `https://myproject-6342.firebaseio.com/${username}.json`;
    return fetch(url).then((res) => res.json());
  },
  addNote(username, note){
    username = username.toLowerCase().trim();
    var url = `https://myproject-6342.firebaseio.com/${username}.json`;
    return fetch(url, {
      method: 'post',
      body: JSON.stringify(note)
    }).then((res) => res.json());
  }

這里出了什么問題?

當發生網絡錯誤時,來自 fetch API 的承諾會以TypeError拒絕,這意味着您必須處理錯誤。 例子:

function _handleError(errorMessage) {
  console.log(errorMessage);
}

fetch('https://api.github.com/users/octocat/repos').then(function(response) {
  if(response.ok) {
    return response.json();
  } else {
    _handleError(`Oops, something went wrong: ${response.status}, ${response.statusText}`);
  }
}).then(function(data) {
   if(data) {
     console.log('success', data);
   }
}).catch(function(error) {
  _handleError(`There has been a problem with your fetch operation: ${error.message}`);
});

更多信息: https : //developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful

好吧,在我的情況下,模擬器互聯網無法正常工作,我按照以下線程進行操作。 Android模擬器無法訪問互聯網

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM