【问题标题】:TypeError: Method called on incompatible receiver undefinedTypeError:在不兼容的接收器上调用的方法未定义
【发布时间】:2018-07-20 15:53:03
【问题描述】:

我尝试修改标准内置方法then(见下文)抛出以下错误:

TypeError: Method Promise.prototype.then called on incompatible receiver undefined at then (<anonymous>) at Promise.then

实现(运行时:浏览器)

(function() {
  console.log(this.Promise);
  const oldThen = this.Promise.prototype.then;
  this.Promise.prototype.then = function() {
    console.log('modification');
    return oldThen(arguments);
  };
})()

Promise.resolve(1).then(fv => {
  console.log(`Promise.resolve().then(..): `, fv);
});

知道这里发生了什么吗?


编辑:

通过箭头函数将this绑定到全局对象,似乎也不起作用:

(function() {
  console.log(this.Promise);
  const oldThen = this.Promise.prototype.then;
  this.Promise.prototype.then = () => {
    console.log('modification');
    console.log(this.Promise); // this is now the global object
    return oldThen(arguments[0]);
  };
})()

Promise.resolve(1).then(fv => {
  console.log(`Promise.resolve().then(..): `, fv);
});

【问题讨论】:

  • 看起来您在任何时候都没有将参数传递给新函数参数
  • @stmfunk 知道了,我可以使用 apply 来传递参数。有没有一种休息、传播或解构的方法,我们可以将所有参数传递给另一个函数(不应用)?

标签: javascript browser promise typeerror


【解决方案1】:

您需要使用正确的this 致电oldThen

return oldThen.apply(this, arguments);

您还需要直接传递参数,而不是包装在数组中。

【讨论】:

  • 谢谢。您能否详细说明为什么this 是错误的?我看到在修改后的函数中,this.Promise.prototype.then 等于Promise.Promise.prototype.then,而不是window.Promise.prototype.then。这就是它破裂的原因吗?我将尝试将其更改为箭头函数,从而将其绑定到外部词法上下文(全局对象)。
  • then() 函数只有一个。您的问题是它需要正确的 this 值。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 哦,那是then内部使用this的问题吗?我很难在上面的编辑示例中看到this 指向的内容,以及在then 中它应该指向的内容。我的意思是,在我的箭头函数中,this 是全局对象。很抱歉造成混乱。
  • @Magnus 如果您正在猴子修补类对象上的方法,那么他们可能需要this 是一个很好的假设。当您引用对象函数时,它会失去对“this”的引用。通常,每当我需要这样的东西时,我都会使用“绑定”方法获取对“旧”函数的引用。
  • @Evert 谢谢。它需要的this 值似乎是Promise.prototype。但是直接传递Promise.prototype 是行不通的。嗯
猜你喜欢
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 2017-01-29
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多