Không thể trực tiếp dùng async function làm effect callback vì nó trả về Promise, nhưng cleanup phải return void.
- Giải pháp: khai báo async function bên trong effect rồi gọi nó.
- Luôn xử lý cleanup để cancel request nếu component unmount.
tsx
useEffect(() => {
const controller = new AbortController()
const fetchData = async () => {
try {
const res = await fetch('/api/data', { signal: controller.signal })
const json = await res.json()
setData(json)
} catch (err) {
if (err.name !== 'AbortError') setError(err)
}
}
fetchData()
return () => controller.abort()
}, [url])You cannot use an async function directly as the effect callback because it returns a Promise, but the cleanup must return void or nothing.
- Declare an async function inside the effect and call it immediately.
- Always handle cleanup to cancel the request if the component unmounts.
tsx
useEffect(() => {
const controller = new AbortController()
const fetchData = async () => {
try {
const res = await fetch('/api/data', { signal: controller.signal })
const json = await res.json()
setData(json)
} catch (err) {
if (err.name !== 'AbortError') setError(err)
}
}
fetchData()
return () => controller.abort()
}, [url])