【问题标题】:"null is not an object" in n.parentNode.removeChild expressionn.parentNode.removeChild 表达式中的“null 不是对象”
【发布时间】:2018-07-14 22:11:28
【问题描述】:

问题: 我从生产网页收到以下错误报告:

TypeErrores6-shim/es6-shim in process
null is not an object (evaluating 'n.parentNode.removeChild')

问题

在低层次上,最可能的情况是什么?

  1. nnull(无论 n 是什么)
  2. n.parentNodenull
  3. argnulln.parentNode.removeChild(arg)

更多详情(如果相关):

我们正在使用 Sentry 错误报告系统来报告错误。

此错误发生在 Mobile Safari 和 Chrome Mobile 下。

源映射似乎已损坏,因此我不知道错误指的是 es6-shim 脚本的哪一行(很可能根本是 es6-shim 问题,因为在 es6-shim 代码中没有出现 removeChild )。

【问题讨论】:

  • 放入一些调试代码以查看调用前的 n 是什么。唯一具有 null parentNode 的元素是文档本身。如果 arg 为 null,我预计会出现不同的错误,例如“arg must be a Node”或类似的。
  • @RobG: 任何你没有添加到 DOM 的元素(或者已经被移除)也有一个 null parentNode,例如,document.createElement("div").parentNodenull
  • @T.J.Crowder——是的,没想到。我也猜想从 DOM 中删除的任何节点都保留了引用。
  • @Piotr Sobczyk 如果您显示一些 html 和 js 代码将会很有帮助。
  • @AabirHussain 问题是我不知道我的源代码中的哪里抛出了异常。我所拥有的只是生产服务器报告的错误消息,代码中没有确切的位置。我的代码库中有几个带有 removeNode 的地方 + 它可能来自一些外部库。

标签: javascript exception web-applications sentry


【解决方案1】:

您可以轻松设置所有三种情况以确定是哪种情况 (also on jsFiddle):

var n, p;

console.log("If n were null:")
try {
  n = null;
  n.parentNode.removeChild(null);
} catch (e1) {
  console.log(e1.message);
}

console.log("If parentNode were null:")
try {
  n = document.createElement("div");
  n.parentNode.removeChild(null);
} catch (e2) {
  console.log(e2.message);
}

console.log("If arg were null:")
try {
  p = document.createElement("div");
  n = document.createElement("div");
  p.appendChild(n);
  n.parentNode.removeChild(null);
} catch (e3) {
  console.log(e3.message);
}
.as-console-wrapper {
  max-height: 100% !important;
}

当我在移动 Chrome 上运行它时,我看到:

如果 n 为空: null 不是对象(评估“n.parentNode”) 如果 parentNode 为空: null 不是对象(评估“n.parentNode.removeChild”) 如果 arg 为空: Node.removeChild 的参数 1('child')必须是 Node 的一个实例

因此,n.parentNode.removeChild(...) 似乎正在被n 引用的对象调用,其中parentNodenull

虽然在es6-shim中报错,但不太可能是es6-shim本身的错误(如你所说,es6-shim中没有removeNode);它更有可能是从提供给 es6-shim 函数之一的回调中抛出的。

【讨论】:

  • 很好的答案。一些非常有用的信息可以帮助我进一步调试它!谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-09-07
  • 2011-10-08
  • 2015-12-30
  • 1970-01-01
  • 2021-02-19
  • 1970-01-01
  • 2021-05-19
  • 2021-09-11
相关资源
最近更新 更多