未处理的承诺拒绝:TypeError:null不是对象(正在评估camera.pictureSize)



我正在创建一个react原生应用程序来使用expo相机模块。

所以我声明了一个相机变量为

let camera: any = null;

我正在返回传递对此的引用,作为:

<Camera style = {{flex: 1, opacity: camOpacity}}
type = {state.type}
ratio = "2:1"
ref = {async (ref) => (camera = ref)}>

但当我运行该应用程序时,它会正常启动,但在尝试拍照时会出现错误:

[Unhandled promise rejection: TypeError: null is not an object (evaluating 'camera.pictureSize')]

此错误发生于:

console.log(camera.pictureSize);

但它也发生在:

console.log(" --> Taking image");
const opts = {
skipProcessing: true,
exif: false,
quality: 0
};
let photo = await camera.takePictureAsync(opts);

当我注释console.log(camera.pictureSize(时,从camera.takePictureAsync(opts(部分

由于某种原因,可能没有检测到引用。

我的包.json是:

"dependencies": {
"expo": "~39.0.2",
"expo-2d-context": "0.0.2",
"expo-asset": "~8.2.0",
"expo-camera": "~9.0.0",
"expo-gl": "~9.1.1",
"expo-image-manipulator": "~8.3.0",
"expo-permissions": "~9.3.0",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-39.0.3.tar.gz",
"react-native-web": "~0.13.12",
"react-native-screens": "~2.10.1",
"react-native-svg": "~12.1.0",
"mem": "^8.0.0",
"@unimodules/core": "~5.5.0"
}

我读到在当前的expo相机版本中有一些这样的错误,但即使我降级了包和依赖项,它仍然是持久的。

如有任何帮助,我们将不胜感激。

编辑:

const photo = async (): Promise<CameraCapturedPicture> | undefined  => {
if(camera){
console.log(" --> Taking image");
const opts = {
skipProcessing: true,
exif: false,
quality: 0
};
return await camera.takePictureAsync(opts);
}
}

console.log(" --> Resizing image");
const {uri} = await ImageManipulator.manipulateAsync(
photo.uri,
[
{ resize: {width: 256, height: 512}},
{ crop: {originX: 0, originY: 128, width: 256, height: 256}}
]
);

我根据Linda的善意建议更改了代码,但现在的错误是Promise不是有效的类型,并且photo.uri没有uri属性

您将cameraref对象初始化为null。因此,在调用它上的任何函数之前,您需要验证它实际上已经设置为Camera,并且不是null。我怀疑这就是你拍照功能出错的原因。请注意,在文档中,他们在调用相机上的方法之前会检查if (this.camera) {

即使相机不是nullconsole.log(camera.pictureSize)也是错误的,因为该属性不存在。pictureSize是传递给Camera组件的道具。它不是相机实例上存在的属性。您应该查看文档。

您可以将变量声明更改为Camera | null,而不是使用any,这将有助于查看可用的属性和方法。

let camera: Camera | null = null;

你可以在你调用的拍照方法中检查camera不是null

const takePicture = async (): Promise<CameraCapturedPicture> | undefined => {
if (camera) {
console.log(" --> Taking image");
const opts = {
skipProcessing: true,
exif: false,
quality: 0
};
return await camera.takePictureAsync(opts);
}
};

或者,您可以在调用该方法之前进行检查,并将camera变量传递到该方法中,以便typescript知道它不是null

const executeTakePicture = async (cam: Camera): Promise<CameraCapturedPicture> => {
console.log(" --> Taking image");
const opts = {
skipProcessing: true,
exif: false,
quality: 0
};
return await cam.takePictureAsync(opts);
};
const maybeTakePicture = async (): Promise<CameraCapturedPicture> | undefined => {
if (camera) {
return await executeTakePicture(camera);
} else {
//...
}
}

最新更新