TypeError:在不兼容的接收方上调用的方法未定义

时间:2018-07-20 15:53:03

标签: javascript browser promise typeerror

我尝试修改标准内置方法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);
});

1 个答案:

答案 0 :(得分:1)

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

return oldThen.apply(this, arguments);

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

相关问题