【Vue】Uncaught (in promise) TypeError: ‘get’ on proxy: property ‘property’ is a read-only and non-configurable data property on the proxy target but the proxy did not return its actual value

エラー内容

Vue2からVue3に移行する際、以下のエラーが出ました。

Uncaught (in promise) TypeError: 'get' on proxy: property 'property' is a read-only and non-configurable data property on the proxy target but the proxy did not return its actual value

原因

調べたところ、Vueのissueに上がってました。

リアクティブオブジェクトを扱う際、Vue2ではgetter/setterを利用していた一方、Vue3ではProxyを利用するようになりました。ちなみに、refは、Vue3でもgetter/setterを使ってます。

私の場合、クラスのインスタンスをリアクティブな値として登録していたのですが、
リアクティブ化を想定されていない、ディープな値までProxy化された結果、このエラーが発生したと認識してます。

対応

shallowReactiveまたはmarkRawを使うことで解決しました。

shallowReactive

通常のreactiveはディープなリアクティブを提供するのに対して、shallowReactiveは浅いリアクティブを提供します。具体的には、ルートレベルのプロパティのみリアクティブとなります。

markRaw

オブジェクトがProxyに変換されないようにします。オブジェクト自体が返されます。

使い方

リアクティブな値の宣言時に、デフォルト値をラップします。
どちらも以下のように、Composition API, Options API のどちらでも使用可能です。

Composition

const foo = shallowReactive({})

Options

<script>
export default {
  data() {
    return {
      foo: shallowReact({})
    }
  }
}
</script>
タイトルとURLをコピーしました