2015-11-18 32 views
0

我在匿名函數(在列21)獲得TypeError: Cannot read property 'enabled' of undefined變量和while循環(15列):JavaScript不能讀取未定義的屬性上聲明較早

var enabled = "unknown"; 
chrome.runtime.sendMessage({request: "Am I enabled?"}, 
    function(response) 
    { 
     enabled = response.enabled; 
    }); 

while(enabled == "unknown") 
{ 
    // wait 
} 

我通常不會編寫JavaScript ,所以我不確定我會在這裏做錯什麼。搜索給了我像var y = null; log(y.property);這樣的結果,根本不是這個問題。

+3

錯誤消息來自匿名函數,並告訴你,'response'沒有定義。當你調用它時,檢查你實際傳遞給函數的內容。 – Teemu

+0

我不知道'sendMessage'函數,但異步方法的第一個參數通常是錯誤,成功時將會是'undefind'。 –

+0

@Teemu它來自匿名函數*和* while循環。我將編輯帖子以澄清這一點。 – demize

回答

3

誤差來源於此行:

enabled = response.enabled; 

因爲response是不確定的。

根據the documentation

如果連接到擴展發生錯誤,回調將不帶任何參數和runtime.lastError將被設置爲錯誤消息被調用。

因此,修改代碼:

var enabled = "unknown"; 
chrome.runtime.sendMessage({request: "Am I enabled?"}, 
function(response) 
{ 
    if (!response) { 
     // TODO: Check runtime.lastError and take an appropriate action 
    } else { 
     enabled = response.enabled; 
     if (enabled) { 
      // TODO: Do the stuff you were planning to do after the while() loop, call a function, etc. 
     } 
    } 
}); 
+0

我被第二次讀錯了,但實際上這是錯誤的根源。事實證明,我忘了實際添加偵聽器,現在它工作正常。 – demize

+0

獎勵:使用承諾而不是回調....讀取它可能需要幾分鐘時間,但它們使代碼更易於維護。 –

相關問題