How can I avoid state of “TypeError: can't acc

2019-01-19 23:55发布

问题:

It seems checking against null works, but is it a correct method? How can I correctly check that object is not dead? And where is the definition of dead object?

回答1:

Dead object would mean an object whose parent document has been destroyed, and the references are removed to eliminate memory leaks in add-ons. So you could check for the element, as:

if( typeof some_element !== 'undefined') {
    //its not dead
}

See Dead Object Reference



回答2:

This is likely due to holding zombie compartments. If you are storing a window in a variable you should use weak reference, otherwise it will keep the process alive.

Great read right here:

https://developer.mozilla.org/en-US/docs/Zombie_compartments

This is how to use weak references: https://developer.mozilla.org/en-US/docs/Components.utils.getWeakReference

A dead object, is holding a strong (keep alive) reference to a DOM element (usually) that persists even after it was destroyed in the DOM.

Sometimes checking if it is undefined or null does not work, a trick I saw once and use sometimes is to check if parentNode exists (so not null or undefined).



回答3:

If you cannot use weak references as suggested by Blagoh, then you can use Components.utils.isDeadWrapper() function to check (added in Firefox 17 but still not really documented):

if (Components.utils.isDeadWrapper(element))
  alert("I won't touch that, it's a dead object");

Unprivileged code doesn't really have a way of recognizing dead objects without triggering an exception. Then again, if an object throws an exception no matter what you do then it is probably dead:

try
{
  String(element);
}
catch (e)
{
  alert("Better not touch that, it's likely a dead object");
}