diff --git a/src/app/error-items/[id]/page.tsx b/src/app/error-items/[id]/page.tsx index cb0d5418..e4e6bf37 100644 --- a/src/app/error-items/[id]/page.tsx +++ b/src/app/error-items/[id]/page.tsx @@ -1,6 +1,6 @@ "use client"; -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import Link from "next/link"; import { useParams, useRouter } from "next/navigation"; import { ArrowLeft, FileQuestion, RefreshCw, Trash2 } from "lucide-react"; @@ -53,11 +53,15 @@ export default function ErrorDetailPage() { // 复习状态由举一反三记录和掌握概率决定,随掌握面板的数据更新 const [masteryStatus, setMasteryStatus] = useState(null); const [savingDifficulty, setSavingDifficulty] = useState(false); + // 保存冲突校验使用的最新读取版本;其他接口只返回局部字段时异步回读刷新 + const updatedAtRef = useRef(undefined); + const pendingUpdatedAt = useRef | null>(null); const fetchItem = useCallback(async (id: string) => { try { const data = await apiClient.get(`/api/error-items/${id}`); setItem(data); + updatedAtRef.current = data.updatedAt; } catch (error) { frontendLogger.error('[ErrorDetail]', 'Failed to fetch error item', { error }); toast.error(t.common?.messages?.loadFailed || 'Failed to load item'); @@ -85,15 +89,32 @@ export default function ErrorDetailPage() { }, [params.id, fetchItem]); const updateItem = useCallback((fields: Partial) => { + if (fields.updatedAt !== undefined) { + updatedAtRef.current = fields.updatedAt; + } setItem((current) => current && { ...current, ...fields }); - }, []); + // 局部更新接口(上传配图、重生成答案等)不返回 updatedAt:回读最新版本, + // 避免随后保存时把本次修改误判为他人并发编辑。 + if (fields.updatedAt === undefined && params.id) { + pendingUpdatedAt.current = apiClient.get(`/api/error-items/${params.id as string}`) + .then((data) => { + updatedAtRef.current = data.updatedAt; + setItem((current) => current && { ...current, updatedAt: data.updatedAt }); + }) + .catch((error) => frontendLogger.warn('[ErrorDetail]', 'Failed to refresh update timestamp', { error })); + } + }, [params.id]); // 保存字段并合并到页面状态,失败时抛出,由各卡片提示;带上读取时的 updatedAt 供并发编辑校验 const saveFields = async (fields: Partial) => { if (!item) return; + if (pendingUpdatedAt.current) { + await pendingUpdatedAt.current; + pendingUpdatedAt.current = null; + } const updated = await apiClient.put>(`/api/error-items/${item.id}`, { ...fields, - ...(item.updatedAt ? { expectedUpdatedAt: item.updatedAt } : {}), + ...(updatedAtRef.current ? { expectedUpdatedAt: updatedAtRef.current } : {}), }); updateItem({ ...fields, ...(updated.updatedAt ? { updatedAt: updated.updatedAt } : {}) }); };