Possible Unhandled Promise Rejection:为何Api.getResp调用失败子对象方法正常?
Api.getResp throw an error but Api.loggedin.getResp work? Great question! Let's break down why you're hitting this Possible Unhandled Promise Rejection error with TypeError: undefined is not a function for Api.getResp, even though Api.loggedin.getResp works perfectly.
The Root Cause: Syntax Error in Api.getResp
Looking at your API definition, the getResp function has invalid syntax in its fetch options that prevents the function from being properly initialized:
// Your broken fetch options const response = await fetch(url, { method, null, { 'content-type' : 'application/json' }, });
Object literals require valid key: value pairs—you can't just include null as a standalone entry, and the content-type header needs to be nested under a headers key. This syntax error causes JavaScript to fail when parsing the Api.getResp function, so the property never gets added to the Api object (hence why Api.getResp logs as undefined).
In contrast, Api.loggedin.getResp doesn't have this syntax mistake, so it's correctly defined and usable.
How to Fix It
Fix the fetch options in Api.getResp to use valid object syntax:
async getResp(url: string, method: string): Promise<Object> { try { const response = await fetch(url, { method: method, body: null, // Explicitly assign null to the `body` key headers: { 'content-type': 'application/json' } // Nest headers under the `headers` key }); // ... rest of your logic } catch (error) { console.log(`fetch url: ${url}, error: ${error}`); } return result; },
Note: I also updated the return type to Promise<Object> since async functions always return a Promise—this is a best practice, though not the direct cause of your error.
Other Things to Rule Out
- Module Import/Export Mismatch: Since
Api.loggedin.getRespworks, your import of theApimodule is correct. This isn't the issue here. - Circular Dependencies: If your
GetDataandApimodules import each other, it could cause partial initialization. However, your logs showApiis a valid object (just missinggetResp), so this is unlikely.
Once you fix the syntax error in Api.getResp, your fetchFeed method should work just like syncData.
内容的提问来源于stack exchange,提问作者timyau

