在 promise 的回调中,this 指向取决于调用该回调函数的上下文环境。如果 promise 是在一个普通函数或方法中创建的,且没有使用箭头函数绑定 this,那么回调中的 this 通常会丢失原有的对象引用,变为 undefined(严格模式下)或全局对象(非严格模式下)。要确保 this 正确指向当前实例,可以在创建 promise 时捕获当前的 this 引用,或者使用箭头函数,因为箭头函数不会创建自己的 this 绑定,而是继承外层作用域的 this。

普通函数中 Promise 回调的 this 指向问题
当在普通函数内部创建 Promise 并使用普通函数作为回调时,回调中的 this 不会自动继承外部函数的 this。这是因为 Promise 的回调是由 Promise 内部机制调用的,其执行上下文是独立的。例如,在一个类的方法中,如果直接在 then 中使用普通函数,this 将不再指向类的实例。

class MyClass {
constructor() {
this.value = 42;
}
createPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(this.value); // 这里的 this 指向 MyClass 实例
}, 1000);
});
}
usePromise() {
this.createPromise().then(function(result) {
console.log(this); // 这里 this 是 undefined (严格模式) 或 window (非严格模式)
console.log(result); // 42
});
}
}
const instance = new MyClass();
instance.usePromise();
上述代码展示了在 then 回调中使用普通函数时,this 的丢失问题。为了解决这个问题,可以使用箭头函数来保持 this 的引用,或者在创建 Promise 之前保存 this 的引用。
立即学习“Java免费学习笔记(深入)”;
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
使用箭头函数解决 this 指向问题
箭头函数不会创建自己的 this 绑定,而是继承定义时所在作用域的 this。因此,在 Promise 回调中使用箭头函数可以确保 this 指向预期的对象。这是现代 JavaScript 中推荐的做法,因为它简洁且避免了常见的 this 陷阱。

class MyClass {
constructor() {
this.value = 42;
}
createPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(this.value); // 这里的 this 指向 MyClass 实例
}, 1000);
});
}
usePromise() {
this.createPromise().then((result) => {
console.log(this); // 这里 this 指向 MyClass 实例
console.log(result); // 42
});
}
}
const instance = new MyClass();
instance.usePromise();
通过上述代码可以看出,使用箭头函数后,then 回调中的 this 正确地指向了 MyClass 的实例。这种方法不仅适用于 Promise 回调,也适用于其他需要保持 this 上下文的场景,如事件处理程序和定时器回调。
基于 Promise 链式调用中 this 的具体行为
在 Promise 链式调用中,每个 then 回调的 this 指向同样遵循上述规则。如果链中的某个回调使用了普通函数,this 可能会丢失;如果使用箭头函数,则 this 会保持一致。这种一致性对于维护对象状态和方法调用至关重要。

















