TaskManager:任务 "firstTask" 已执行,但看起来尚未定义。确保 "TaskManager.defineTask" 在初始化阶段被调用

TaskManager: Task "firstTask" executed but looks like it's not defined. Make sure "TaskManager.defineTask" is called during initialization phase

我是 运行 一个 EAS 应用程序,我必须使用 Expo-Task-Manager 来处理后台位置。当我的应用程序构建时,我遇到了这个错误:

TaskManager: Task "firstTask" has been executed but looks like it is not defined. Please make 
sure that "TaskManager.defineTask" is called during initialization phase.

下面是我在我的应用程序中执行任务管理器的代码,但我很难找到在“初始化阶段”调用它的位置。

import * as TaskManager from 'expo-task-manager'
import * as BackgroundFetch from 'expo-background-fetch'
import * as Location from 'expo-location'

const LOCATION_TASK_NAME = 'background-location-task'

useFocusEffect(
    React.useCallback(()=>{

       const requestBackgroundPermissions = async() =>{
       const {status} = await Location.requestBackgroundPermissionsAsync()
         if(status === 'granted'){
           await Location.startLocationUpdatesAsync('firstTask',{
             accuracy: Location.Accuracy.Balanced,
       });
     }
     requestBackgroundPermissions()

    },
    [],
   ),
 )

//在useFocusEffect之外

TaskManager.defineTask('firstTask',({data,errror})=>{
    if(error){
      alert('Something went wrong with background locations')
    }
    if(data){
      alert('Something went right with background locations')
      const{locations} = data
    }
})

因此,如果您 运行 遇到此问题,请尝试将您的任务管理器移动到您的 App.js 文件中。当应用程序加载时,任务管理器将成为初始化阶段的一部分。如果您有任何问题,请随时与我们联系,但它应该看起来像这样:

import React from "react"
import {StyleSheet} from 'react-native'
import * as TaskManager from 'expo-task-manager'
import * as BackgroundFetch from 'expo-background-fetch'
import * as Location from 'expo-location'

const LOCATION_TASK_NAME = 'background-location-task'

TaskManager.defineTask('firstTask',({data,errror})=>{
    if(error){
      alert('Something went wrong with background locations')
    }
    if(data){
      alert('Something went right with background locations')
      const{locations} = data
    }
})

export default function App(){

return <AppFile/>

}