Chrome 扩展中的突然错误:"cannot access before initialization"

Sudden error in Chrome extension: "cannot access before initialization"

在 Chrome 扩展中捕获激活或更新的选项卡并从中获取 url 我使用类似

的结构
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.url) run(tab);
});

chrome.tabs.onActivated.addListener(info => {
    chrome.tabs.get(info.tabId, run);
});

const processingTabId = {};

function run(tab) {
    if (processingTabId[tab.id]) return;
    processingTabId[tab.id] = true;

    let newUrl = new URL(tab.pendingUrl || tab.url)
    currentHost = newUrl.host;

有些日子它就像一个魅力,而且这个扩展正在使用中。但是今天,没有 Chrome 更新或任何代码更改,我突然意识到,我在任何情况下都没有 url,不是在选项卡激活时,不是在选项卡更新(刷新)时。查看扩展后端我意识到一个错误,它从来没有出现过:

Cannot access 'processingTabId' before initialization

并且标记了这些代码行:

function run(tab) {
    if (processingTabId[tab.id]) return;

有人知道这个错误是什么意思,如何修复以及为什么突然发生?

您需要先初始化 processingTabId,然后再调用使用它的 run() 函数。因此,在添加调用 run().

的侦听器之前,将声明放在顶部
const processingTabId = {};

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.url) run(tab);
});

chrome.tabs.onActivated.addListener(info => {
    chrome.tabs.get(info.tabId, run);
});

function run(tab) {
    if (processingTabId[tab.id]) return;
    processingTabId[tab.id] = true;

    let newUrl = new URL(tab.pendingUrl || tab.url)
    currentHost = newUrl.host;