首选项报错:"Using this inside stand-alone functions is notsupported"如何解决 ?

首选项报错:"Using this inside stand-alone functions is notsupported"如何解决

阅读 2.1k
1 个回答

问题原因

以下代码报错:"Using this inside stand-alone functions is notsupported"。

async function getPreferences() { 
  return dataPreferences.getPreferences(getContext(this), PREFERENCES_NAME) 
}

解决措施

不支持在独立的函数中使用this,可以在函数外面定义一个变量let context = getContext(),再将context 给下面的函数使用。

示例如下:

import dataPreferences from '@ohos.data.preferences'; 
 
let context = getContext(this) 
let options: dataPreferences.Options = { name: 'myStore', dataGroupId: 'myId' }; 
 
async function getPreferences() { 
  return dataPreferences.getPreferences(context, options) 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进