首页 > 解决方案 > aurelia中“未处理的承诺拒绝:TypeError”的可能原因是什么?

问题描述

我一直从事 Aurelia 开发,但休息了两个月。现在我已经开始了一个新项目,在尝试使用http-fetch-client.

控制台显示:

aurelia-fetch-client.js?a909:199 OPTIONS http://url.com/api/login net::ERR_CONNECTION_REFUSED

index.js?07f7:248 Possible Unhandled Promise Rejection: TypeError: Failed to fetch

网络选项卡显示:

Request URL: http://url.com/api/login
Referrer Policy: no-referrer-when-downgrade

令我惊讶的是,我之前的项目(两个月前成功执行获取客户端请求)现在也显示此错误。任何人都可以就这个问题提供见解吗?为什么我会遇到这种情况?

标签: typescripthttprequestaurelia

解决方案


听起来您正在执行 async/await,并且您还没有将await呼叫包装在try/catch.

某些版本的 Aurelia 使用 Bluebird 作为 Promise shim,您可以使用它们的全局拒绝事件来处理这些问题。

这就是它的样子。

// NOTE: event name is all lower case as per DOM convention
window.addEventListener("unhandledrejection", function(e) {
    // NOTE: e.preventDefault() must be manually called to prevent the default
    // action which is currently to log the stack trace to console.warn
    e.preventDefault();
    // NOTE: parameters are properties of the event detail property
    var reason = e.detail.reason;
    var promise = e.detail.promise;
    // See Promise.onPossiblyUnhandledRejection for parameter documentation
});

// NOTE: event name is all lower case as per DOM convention
window.addEventListener("rejectionhandled", function(e) {
    // NOTE: e.preventDefault() must be manually called prevent the default
    // action which is currently unset (but might be set to something in the future)
    e.preventDefault();
    // NOTE: parameters are properties of the event detail property
    var promise = e.detail.promise;
    // See Promise.onUnhandledRejectionHandled for parameter documentation
});

当然,您可能正在使用不同的 Promise shim。但是,最终,try/catch是你的答案。


推荐阅读