You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用react-native-gesture-handler长按后Expo Go应用崩溃求助

长按手势中调用expo-router的router.push导致应用崩溃

问题场景

仅在react-native-gesture-handler的长按手势回调中调用router.push时应用崩溃,替换为console.log()则无异常。

代码示例

import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import { router } from 'expo-router';

// ...

const longPressGesture = Gesture.LongPress().onEnd((_e, success) => {
  if (success) {
    router.push('/products/edit'); // 此处触发崩溃
  }
});

// ...

<GestureDetector gesture={longPressGesture}>
  <ScrollView>
    {products.map((product, index) => (
      <Card key={index} />
    ))}
  </ScrollView>
</GestureDetector>

环境信息

  • react-native-gesture-handler: 2.14.0
  • expo: 50.0.5
  • 已完成操作:根布局已用GestureHandlerRootView包裹,测试环境为Expo Go模拟器

解决方案

  • 用requestAnimationFrame包裹路由跳转
    手势回调的执行上下文可能和React更新周期冲突,延迟执行跳转让React完成当前手势的收尾工作:

    const longPressGesture = Gesture.LongPress().onEnd((_e, success) => {
      if (success) {
        requestAnimationFrame(() => {
          router.push('/products/edit');
        });
      }
    });
    
  • 改用useRouter钩子获取实例
    直接导入的router在某些手势上下文可能存在实例异常,改用组件内的钩子获取:

    import { useRouter } from 'expo-router';
    
    // 组件内部声明
    const router = useRouter();
    
    const longPressGesture = Gesture.LongPress().onEnd((_e, success) => {
      if (success) {
        router.push('/products/edit');
      }
    });
    
  • 强制回调在JS线程执行
    给手势添加runOnJS(true),确保回调逻辑在JS线程而非UI线程执行,避免路由跳转时的线程冲突:

    const longPressGesture = Gesture.LongPress()
      .runOnJS(true)
      .onEnd((_e, success) => {
        if (success) {
          router.push('/products/edit');
        }
      });
    
  • 短延迟执行跳转
    如果以上方法无效,尝试用setTimeout加100ms左右的延迟:

    const longPressGesture = Gesture.LongPress().onEnd((_e, success) => {
      if (success) {
        setTimeout(() => {
          router.push('/products/edit');
        }, 100);
      }
    });
    

内容的提问来源于stack exchange,提问作者InfamousCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 15:43:26