setTimeout中this丢失是因为其回调以普通函数方式执行,不保留调用时的this;需用bind(this)显式绑定,如setTimeout(this.handleClick.bind(this), 100)。

直接用 bind 把当前 this 绑定到回调函数上,就能让 setTimeout 里访问到正确的上下文。
为什么 setTimeout 里 this 会丢失?
setTimeout 内部调用回调时,是以普通函数方式执行的,不保留调用时的 this。比如在对象方法里写 setTimeout(this.handleClick, 100),回调执行时 this 就变成了 window(非严格模式)或 undefined(严格模式)。
用 bind 显式绑定 this
在传入回调前,用 bind(this) 创建一个新函数,把当前实例的 this 固定住:
setTimeout(this.handleClick.bind(this), 100);- 如果需要传参,可以一起写:
setTimeout(this.handleData.bind(this, 'arg1', 'arg2'), 100); -
bind返回的是新函数,不会影响原方法,安全可靠
其他等效写法对比
bind 是最直白的方案,但还有几种常见替代方式:
- 箭头函数:
setTimeout(() => this.handleClick(), 100)—— 利用词法作用域继承外层this - 闭包保存:
const self = this; setTimeout(function() { self.handleClick(); }, 100) - class 字段箭头写法(React 常用):
handleClick = () => { ... },再直接传setTimeout(this.handleClick, 100)
注意 bind 的执行时机
bind 要在 setTimeout 调用前执行,不能写成 setTimeout(this.handleClick.bind, this, 100) 这种错误形式。正确写法必须是 this.handleClick.bind(this),括号不能漏。
不复杂但容易忽略

















