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 @ 2024-08-14 03:36  冰凉小手  阅读(82)  评论(0编辑  收藏  举报