fix(h5-partner): allow reopening WeChat image picker after cancel

Avoid resetting JSSDK on each pick and unlock cancel paths so camera/album can be opened again.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-02 17:11:19 +08:00
parent 07fbb74485
commit 5deffbdbfb
4 changed files with 56 additions and 22 deletions
@@ -21,6 +21,10 @@ type OssUploadFieldProps = {
const DEFAULT_MAX_MB = 10; const DEFAULT_MAX_MB = 10;
function isCancelError(msg: string): boolean {
return /cancel|取消/i.test(msg);
}
function formatWechatUploadError(e: unknown): string { function formatWechatUploadError(e: unknown): string {
const msg = e instanceof Error ? e.message : '无法打开相册'; const msg = e instanceof Error ? e.message : '无法打开相册';
const formatted = formatChooseImageFailMessage(msg); const formatted = formatChooseImageFailMessage(msg);
@@ -46,6 +50,7 @@ export default function OssUploadField({
label, label,
}: OssUploadFieldProps) { }: OssUploadFieldProps) {
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const pickingRef = useRef(false);
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [showAlbumFallback, setShowAlbumFallback] = useState(false); const [showAlbumFallback, setShowAlbumFallback] = useState(false);
@@ -63,7 +68,7 @@ export default function OssUploadField({
useEffect(() => { useEffect(() => {
if (!useWechatPicker) return; if (!useWechatPicker) return;
weixinSdk.reset(); // 仅预热,勿在每次点击时 reset,否则取消后再点常无法调起
void weixinSdk.init().catch(() => { void weixinSdk.init().catch(() => {
/* 点击上传时会再次初始化 */ /* 点击上传时会再次初始化 */
}); });
@@ -96,31 +101,37 @@ export default function OssUploadField({
} }
async function pickWechatImage() { async function pickWechatImage() {
setUploading(true); if (pickingRef.current || uploading) return;
pickingRef.current = true;
setError(''); setError('');
try { try {
weixinSdk.reset(); // 不要每次 reset:会打断 JSSDK,取消后再点经常无法调起相机/相册
await weixinSdk.init(); await weixinSdk.init();
// 选图 + 上传须在同一个队列任务内完成,避免嵌套 enqueueUpload 死锁
await enqueueUpload(async () => {
const files = await weixinSdk.chooseImages({ const files = await weixinSdk.chooseImages({
count: 1, count: 1,
sourceType: ['album', 'camera'], sourceType: ['album', 'camera'],
}); });
if (!files?.[0]) return; // 取消或未选图:直接结束,允许再次点击
await persistUpload(files[0]); if (!files?.length) return;
});
} catch (e) { setUploading(true);
const msg = e instanceof Error ? e.message : '无法打开相册'; try {
if (/cancel/i.test(msg)) return; // 仅串行化实际上传,选图本身不占上传锁,避免取消后锁态异常
throw e; await enqueueUpload(() => persistUpload(files[0]!));
} finally { } finally {
setUploading(false); setUploading(false);
} }
} catch (e) {
const msg = e instanceof Error ? e.message : '无法打开相册';
if (isCancelError(msg)) return;
throw e;
} finally {
pickingRef.current = false;
}
} }
async function pickFile() { async function pickFile() {
if (uploading) return; if (uploading || pickingRef.current) return;
setError(''); setError('');
if (useWechatPicker) { if (useWechatPicker) {
@@ -128,7 +139,7 @@ export default function OssUploadField({
await pickWechatImage(); await pickWechatImage();
} catch (e) { } catch (e) {
const msg = e instanceof Error ? e.message : '无法打开相册'; const msg = e instanceof Error ? e.message : '无法打开相册';
if (/cancel/i.test(msg)) return; if (isCancelError(msg)) return;
const formatted = formatWechatUploadError(e); const formatted = formatWechatUploadError(e);
setError(`${formatted},可改从系统相册选择`); setError(`${formatted},可改从系统相册选择`);
setShowAlbumFallback(true); setShowAlbumFallback(true);
@@ -134,7 +134,6 @@ export default function StoreCreatePage() {
useEffect(() => { useEffect(() => {
if (step !== 2 || !isWechatEnv()) return; if (step !== 2 || !isWechatEnv()) return;
weixinSdk.reset();
void weixinSdk.init().catch(() => { void weixinSdk.init().catch(() => {
/* OssUploadField 点击时会再次初始化 */ /* OssUploadField 点击时会再次初始化 */
}); });
+29 -6
View File
@@ -17,10 +17,14 @@ function delay(ms: number): Promise<void> {
return new Promise((resolve) => window.setTimeout(resolve, ms)); return new Promise((resolve) => window.setTimeout(resolve, ms));
} }
function isChooseImageCancelMessage(msg: string): boolean {
return /cancel|取消/i.test(msg.trim());
}
/** 将微信 chooseImage / getLocalImgData fail 的 errMsg 转为用户可读文案 */ /** 将微信 chooseImage / getLocalImgData fail 的 errMsg 转为用户可读文案 */
export function formatChooseImageFailMessage(errMsg: string): string { export function formatChooseImageFailMessage(errMsg: string): string {
const msg = errMsg.trim() || '无法打开相册'; const msg = errMsg.trim() || '无法打开相册';
if (/cancel/i.test(msg)) return ''; if (isChooseImageCancelMessage(msg)) return '';
if (/offline verifying|permission value is offline/i.test(msg)) { if (/offline verifying|permission value is offline/i.test(msg)) {
return '微信权限验证中,请稍候再试或刷新页面后重新选择图片'; return '微信权限验证中,请稍候再试或刷新页面后重新选择图片';
@@ -54,7 +58,7 @@ async function reportChooseImageEvent(
stage: 'jssdk' | 'choose' | 'read' | 'empty'; stage: 'jssdk' | 'choose' | 'read' | 'empty';
}, },
) { ) {
if (/cancel/i.test(payload.errMsg)) return; if (isChooseImageCancelMessage(payload.errMsg)) return;
try { try {
const headers: Record<string, string> = { const headers: Record<string, string> = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@@ -159,19 +163,38 @@ function invokeChooseImage(
sourceType: Array<'album' | 'camera'>, sourceType: Array<'album' | 'camera'>,
): Promise<string[]> { ): Promise<string[]> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let settled = false;
const finish = (fn: () => void) => {
if (settled) return;
settled = true;
window.clearTimeout(hangTimer);
fn();
};
// 极端机型取消后无回调:最长等待后按取消解锁,避免业务侧 uploading 永久卡住
const hangTimer = window.setTimeout(() => {
finish(() => resolve([]));
}, 180_000);
window.wx!.chooseImage!({ window.wx!.chooseImage!({
count, count,
sizeType: ['compressed'], sizeType: ['compressed'],
sourceType, sourceType,
success: (res) => resolve(res.localIds ?? []), success: (res) => finish(() => resolve(res.localIds ?? [])),
fail: (err) => { fail: (err) => {
const raw = err.errMsg || '无法打开相册'; const raw = err.errMsg || '无法打开相册';
if (/cancel/i.test(raw)) { if (isChooseImageCancelMessage(raw)) {
resolve([]); finish(() => resolve([]));
return; return;
} }
const formatted = formatChooseImageFailMessage(raw); const formatted = formatChooseImageFailMessage(raw);
reject(new Error(formatted || raw)); finish(() => reject(new Error(formatted || raw)));
},
// 部分微信版本取消只走 complete
complete: () => {
window.setTimeout(() => {
finish(() => resolve([]));
}, 300);
}, },
}); });
}); });
+1
View File
@@ -51,6 +51,7 @@ export type WxApi = {
sourceType?: Array<'album' | 'camera'>; sourceType?: Array<'album' | 'camera'>;
success?: (res: { localIds: string[] }) => void; success?: (res: { localIds: string[] }) => void;
fail?: (res: { errMsg: string }) => void; fail?: (res: { errMsg: string }) => void;
complete?: (res?: { errMsg?: string }) => void;
}) => void; }) => void;
getLocalImgData: (options: { getLocalImgData: (options: {
localId: string; localId: string;