探索vue3报错:[Vue warn]: Vue received a Component which was made a reactive object. This can lead to ...

[Vue warn]: Vue received a Component which was made a reactive object. This can lead to unnecessary performance overhead, and should be avoided by marking the component with markRaw or using shallowRef instead of ref

产生:这个警告是在vue3使用组件的时候抛出来的
产生时期:内部方法_createVNode调用产生的
部分源码如下

  const shapeFlag = isString(type)
    ? ShapeFlags.ELEMENT
    : __FEATURE_SUSPENSE__ && isSuspense(type)
    ? ShapeFlags.SUSPENSE
    : isTeleport(type)
    ? ShapeFlags.TELEPORT
    : isObject(type)
    ? ShapeFlags.STATEFUL_COMPONENT
    : isFunction(type)
    ? ShapeFlags.FUNCTIONAL_COMPONENT
    : 0

  if (__DEV__ && shapeFlag & ShapeFlags.STATEFUL_COMPONENT && isProxy(type)) {
    type = toRaw(type)
    warn(
      `Vue received a Component which was made a reactive object. This can ` +
        `lead to unnecessary performance overhead, and should be avoided by ` +
        `marking the component with \`markRaw\` or using \`shallowRef\` ` +
        `instead of \`ref\`.`,
      `\nComponent that was made reactive: `,
      type
    )
  }

其中,
1.DEV为true
2.shapeFlag和shapeFlag.STATEFUL_COMPONENT都返回4
3.重点在于isProxy方法,此方法主要是检测是否存在__v__isReactive属性
shallowReactive是存在的,返回true
markRaw和shallowRef是不存在,返回undefined
打印如下:

console.error(shallowReactive(sonComponent).__v_isReactive)
console.error(markRaw(sonComponent).__v_isReactive)
console.error(shallowRef(sonComponent).__v_isReactive)
控制台打印验证

因此使用markRaw和shallowRef是可以的,使用shallowReactive警告会一直存在
具体为什么这么设计,后续有时间继续探索!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容