uni-app中getCurrentPages在onLoad上运行时,h5正常但app报错

uni-app中getCurrentPages在onLoad上运行时,h5正常但app报错

开发环境 版本号 项目创建方式
Mac macOS 12.6.7 HBuilderX

操作步骤:

onReady(){
console.log('onReady');
let aa = getCurrentPages();
console.log(aa);
},

预期结果:

正常打印

实际结果:

[Vue warn]: Error in onReady hook: "TypeError: getCurrentPages is not a function"

bug描述:

[Vue warn]: Error in onReady hook: "TypeError: getCurrentPages is not a function"  
(found at pages/dynamic/detail.vue:1)
se
o.config.errorHandler
Ze
Ye
Ke
Hr
fv
mounted
Ke
Hr
(anonymous)
wv
Ke
Fn.$emit
subscribeHandler
(anonymous)
va
$v
CallbackManager.consume
TaskCenter.callback
callback
(anonymous)
receiveTasks
callJS
global.(anonymous function)
(anonymous)
(anonymous)
_emit
emit
(anonymous)
TypeError: getCurrentPages is not a function
at onReady (detail.vue:230)
at Ke ()
at o.Hr [as __call_hook] ()
at fv ()
at o.mounted ()
at Ke ()
at o.Hr [as __call_hook] ()
at Array.<anonymous> ()
at Hn.wv ()
at Ke ()

更多关于uni-app中getCurrentPages在onLoad上运行时,h5正常但app报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app中getCurrentPages在onLoad上运行时,h5正常但app报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html


uni-app 中使用 getCurrentPages() 函数时,如果在 onLoad 生命周期钩子中调用,可能会导致在 H5 环境中正常运行,但在 App 环境中报错。这通常是因为 getCurrentPages() 返回的页面栈在 onLoad 时可能还没有完全初始化。

原因分析

  • getCurrentPages() 返回的是当前页面栈的数组,表示已经打开的页面实例。
  • onLoad 生命周期钩子中,页面可能还没有完全加载到页面栈中,因此在 App 环境中调用 getCurrentPages() 可能会返回 undefined 或空数组。

解决方案

  1. 延迟调用:将 getCurrentPages() 的调用延迟到 onReadyonShow 生命周期钩子中,确保页面已经完全加载到页面栈中。

    onReady() {
      const pages = getCurrentPages();
      console.log(pages);
    }
    
  2. 检查返回值:在 onLoad 中调用 getCurrentPages() 时,先检查返回值是否有效。

    onLoad() {
      const pages = getCurrentPages();
      if (pages && pages.length > 0) {
        console.log(pages);
      } else {
        console.log('页面栈未初始化');
      }
    }
    
  3. 使用 this.$scope:在某些情况下,可以直接使用 this.$scope 来获取当前页面的实例。

    onLoad() {
      const currentPage = this.$scope;
      console.log(currentPage);
    }
回到顶部