Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

computed 和 watch 不会在自定义组件或页面卸载时自动移除监听吗? #106

Open
lixilin322 opened this issue Dec 23, 2024 · 2 comments

Comments

@lixilin322
Copy link

在写业务逻辑时,发现computedwatch 并不会在自定义组件或页面卸载时自动移除监听,如果watch内部使用了this,也就是当前组件实例或页面实例,则该实例不会被释放,如果多次进入同一页面,watch监听会重复绑定多个,严重影响性能和业务逻辑。

@LastLeaf
Copy link
Member

LastLeaf commented Dec 24, 2024

computedwatch 基于数据监听器。无论组件或页面是否已经 detached ,只要组件执行了 this.setData (或者属性被更改了),就必然会触发数据监听器,进而触发 computedwatch 。监听器本身随着组件的 this 被垃圾回收而释放。

如果观测到 computedwatch 被触发,移除对应的 this.setData 或父组件触发的属性更新即可。

P.S. 在 watch 内部使用组件的组件或者页面的 this 并不会阻止 this 被垃圾回收,请放心使用。

@LastLeaf
Copy link
Member

如果你试图间隔循环更新,例如:

Component({
  watch: {
    someField: () => {
      setTimeout(() => this.setData({ someField: ... }), 1000)
    }
  }
})

请确保有个合适的终止条件,例如在 detached 之后不要再触发。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants