TypeError: Cannot read private member xxx from an object whose class did not declare it

问题发生场景

在vue3中使用reactive响应式转换一个带有私有属性的对象。

大致原因

在js中,代理Proxy和类的私有属性无法公用,而vue3的响应式是基于代理的。

简单例子

function logReads(target) {
return new Proxy(target, {
get(obj, prop, receiver) {
console.log(prop);
return Reflect.get(obj, prop, receiver)
},
});
}
class TodoList {
#items = [];
threshold = 50;
countCheap() {
return this.#items.reduce((n, item) => item.price < this.threshold ? n : n + 1, 0);
}
}
let list = logReads(new TodoList());
list.countCheap(); // TypeError: Cannot read private member #items from an object whose class did not declare it

github上的讨论

https://github.com/tc39/proposal-class-fields/issues/106

posted @   冰凉小手  阅读(183)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示