【问题标题】:Clearing an item from AsyncStorage - React native从 AsyncStorage 中清除项目 - 反应原生
【发布时间】:2021-01-09 12:34:22
【问题描述】:

我是新手,目前我正在开发一个需要更新异步存储中特定值的项目。我尝试使用此代码 await AsyncStorage.removeItem(key); 从 Asyncstorage 中清除一个项目,但是当我使用它时,控制台会引发类似 'await' is only allowed within async functions 的错误。但我使用的是异步函数

  const getExceedCountData = async () => {
    const token = await AsyncStorage.getItem("@userToken")
    const exceedcount = await AsyncStorage.getItem("@exceedCount")
    if(!exceedcount){
        try {
        setLoading(true)
        axios
            .get(constants.BASE_URL + "getexceedcount?token=" +token)
            .then(response => {
                if(response.data.status == 1){
                    try {
                        await AsyncStorage.removeItem("@exceedCount");
                    }
                    catch(exception) {
                        console.log('Error Occured');
                    }
                    AsyncStorage.setItem("@exceedCount", response.data.result);
                    setExceedCount({ value:response.data.result, error: '' })
                }
            })
            .catch(error => {
                console.log(error);
            });
        } catch(error) {
            console.log(error);
        }
    }else{
        setExceedCount({ value:exceedcount, error: '' })
    }
  }

我不知道为什么会出现这个问题。任何帮助都是可观的。

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    您需要将函数标记为异步。

    .then(async (response) => {
                    if(response.data.status == 1){
                        try {
                            await AsyncStorage.removeItem("@exceedCount");
                        }
                        catch(exception) {
                            console.log('Error Occured');
                        }
                        AsyncStorage.setItem("@exceedCount", response.data.result);
                        setExceedCount({ value:response.data.result, error: '' })
                    }
                })
    

    【讨论】:

      【解决方案2】:

      .then 内的函数范围未声明为异步。这应该可以解决您的问题:

      .then(async response => {
          if(response.data.status == 1){
             try {
                await AsyncStorage.removeItem("@exceedCount");
             } catch(exception) {
                console.log('Error Occured');
             }
             AsyncStorage.setItem("@exceedCount", response.data.result);
             setExceedCount({ value:response.data.result, error: '' })
          }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多