You need to enable JavaScript to run this app. React Native 组件卸载时调用GraphQL订阅unsubscribe抛出undefined类型错误
优惠活动
大模型
产品
解决方案
定价
更多

React Native 组件卸载时调用GraphQL订阅unsubscribe抛出undefined类型错误

报错触发原因
  • 核心是异步执行时序的断层问题,你把订阅监听器的初始化逻辑放在了componentDidMount中await this.getPosts()的后面,意味着必须等获取帖子的网络请求完全返回,才会给this.createSoundwaveListener、this.deleteSoundwaveListener两个变量赋值:
    1. 如果在getPosts等待网络返回的间隙,组件因为导航栈切换、路由重定向、权限拦截等原因触发了componentWillUnmount,两个监听器变量还没完成初始化,值为undefined。此时执行取消订阅逻辑调用.unsubscribe(),就会直接抛出「undefined 不是对象」的错误——这也是为什么你刚导航进页面、还没做任何操作就触发报错的原因。
    2. 如果getPosts请求本身抛出未捕获的异常,后续的监听器初始化代码会直接中断,两个变量永远保持undefined状态,等组件卸载时执行取消订阅逻辑就会触发崩溃。
  • 取消订阅逻辑没有做兼容处理:当前代码直接对监听器变量调用unsubscribe()方法,没有校验变量是否已经完成初始化、是否存在,只要变量是undefined就会直接报错。
修复方案
  • 第一优先级:给取消订阅逻辑做空值兼容,彻底避免未初始化就调用方法的崩溃
    把原来的componentWillUnmount代码替换为支持可选链判断的版本:
    componentWillUnmount() {
      // 只有监听器真实完成初始化、存在实例时,才执行取消订阅
      this.createSoundwaveListener?.unsubscribe();
      this.deleteSoundwaveListener?.unsubscribe();
    }
    
  • 调整初始化顺序,把监听器的创建逻辑移到异步请求的前面,不要让网络请求阻塞监听器初始化:
    把componentDidMount中的两个订阅代码块,提前到await this.getPosts()之前执行,避免网络等待过程中组件被卸载导致的未赋值问题,调整后的核心顺序示例:
    componentDidMount = async () => {
      // 先绑定导航参数
      this.props.navigation.setParams({toggleTrending: this.toggleSortTrending});
      this.props.navigation.setParams({toggleNewest: this.toggleSortNewest});
      this.props.navigation.setParams({toggleForYou: this.toggleSortForYou});
      this.props.navigation.setParams({toggleDistance: this.toggleDistance});
    
      // 优先初始化两个GraphQL订阅监听器,不等待其他异步任务
      this.createSoundwaveListener = API.graphql(
        graphqlOperation(onCreateSoundwave),
      ).subscribe({
        next: postData => {
          const newPost = postData.value.data.onCreateSoundwave;
          const prevPosts = this.state.posts.filter(post => post.id !== newPost.id);
          this.setState({posts: [newPost, ...prevPosts]});
        },
      });
    
      this.deleteSoundwaveListener = API.graphql(
        graphqlOperation(onDeleteSoundwave),
      ).subscribe({
        next: postData => {
          const deletedPost = postData.value.data.onDeleteSoundwave;
          const updatedPosts = this.state.posts.filter(post => post.id !== deletedPost.id);
          this.setState({posts: updatedPosts});
        },
      });
    
      // 再执行定位、获取帖子列表的异步逻辑
      Geolocation.getCurrentPosition(
        position => {
          this.setState({
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          });
        },
        error => console.log('currentLocation ERROR: ' + error),
        {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
      );
      
      await this.getPosts();
    }
    
  • 给getPosts方法加上错误捕获,避免未处理的请求异常中断后续代码执行:
    getPosts = async () => {
      try {
        const result = await API.graphql(graphqlOperation(listSoundwaves));
        this.setState({ 
          posts: result.data.listSoundwaves.items,
          isLoading: false
        })
      } catch (err) {
        console.log('帖子列表加载失败:', err);
        // 就算加载失败也要关闭loading状态,避免页面卡死
        this.setState({ isLoading: false });
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.09 05:45:03