[英]Event.preventDefault does not seem to work (async context)
我意識到有幾個關於preventDefault
不起作用的問題。 但我的問題是關於一個相當簡單的情況,你有一個async
function 並拋出一個錯誤:
throw 'error of some kind';
... 然后你想要一個“清理” function 來捕獲所有此類錯誤。 然后按預期工作:
window.addEventListener('unhandledrejection', function (event) {
console.log( 'unhandled Promise rejection, event: ', event );
// event.preventDefault();
});
但是如果我取消注釋event.preventDefault()
,我希望看到throw
消息不會然后作為錯誤打印到控制台。 但它總是被打印出來。
我檢查以確保在這種情況下該event
確實可以cancelable
。 它聲稱是這樣。
PS 從我的實驗來看似乎是這樣
window.onunhandledrejection = event => {
...
};
只是為同一個“unhandledrejection”事件實現同一個監聽器的另一種方式。 使用event.preventDefault()
似乎也不起作用。
編輯
經過幾次實驗后,我似乎發現我能找到防止這種情況的唯一方法是在某個時候吞下錯誤(使用try...catch
),最好是在堆棧中最高的async
調用(或者更確切地說是在序列中) async
函數的調用),如果可以確定的話。
window.addEventListener('unhandledrejection', event => { console.log(event.cancelable, event.reason, "unhandled rejection") event.preventDefault() event.stopPropagation() event.stopImmediatePropagation() return false }) async function x() { console.log('async') throw "async error" } x() new Promise(res => { console.log('prom') throw "prom error" })
在 Firefox 76 上驗證。直接承諾也不起作用。 看起來像一個錯誤。 可能應該向 Mozilla 的 Firefox 跟蹤器提出問題。
注意:這不是解決方案。 除了提交錯誤並修復它之外,是否有任何解決方案值得懷疑。
window.onerror = msg => console.log(msg) || false window.addEventListener('unhandledrejection', event => { console.log(event.cancelable, event.reason, "unhandled rejection") event.preventDefault() event.stopPropagation() event.stopImmediatePropagation() return false }) async function x() { console.log('async') throw "async error" } x() new Promise(res => { console.log('prom') throw "prom error" })
在 Firefox97 上重現。 似乎錯誤日志是在觸發'unhandledrejection'
處理程序之前打印在控制台上的,因此event.preventDefault()
無法提供幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.