uniapp 在onShow使用getCurrentPages会出现报错

uniapp 在onShow使用getCurrentPages会出现报错

我用的红米k80真机跑的,用的标准基座,使用的vue2,在进入页面的时候调用getCurrentPages这个方法会报错误 Property or method "toJSON" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

image

image


12 回复

hbuildx版本是4.66版本

稳定复现吗?重新运行一下或者删除 unpackage 试过吗?运行到安卓模拟器呢?

回复 DCloud_UNI_yuhe: 稳定复线,其他机型不会

使用的是哪个版本的hbuilderx?

你把console.log打印getCurrentPages()的注释掉还会吗

或者注释掉getCurrentPages相关的,看还会报错嘛

回复 1***@qq.com: 应该是打印的问题吧,好像打印this.$refs和this.$parent也会报类似的错

你打印这个试下,getCurrentPages()[0].$vm

回复 1***@qq.com: 或者打印getCurrentPages()[0].route,应该就不会报错

onShow 中调用 getCurrentPages() 返回的页面实例包含循环引用结构,直接绑定到模板会导致 Vue 渲染时报 toJSON 相关错误。

解决方案:

  1. 避免直接绑定页面实例
    不要将 getCurrentPages() 返回的完整实例直接赋值给 data 中的响应式变量。页面实例包含大量内部属性(如路由、导航状态等),其中可能包含不可序列化的对象。

  2. 按需提取数据
    若需使用页面栈信息,应仅提取需要的数据字段(如路由路径、参数等):

    onShow() {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      this.pageRoute = currentPage.route; // 仅存储路径字符串
      this.pageOptions = currentPage.options; // 参数对象
    }
    
  3. 使用计算属性处理数据
    对于需要复杂处理的场景,可通过计算属性返回安全数据:

    computed: {
      safePageInfo() {
        const page = getCurrentPages().pop();
        return { route: page?.route, options: page?.options };
      }
    }
回到顶部