Usually, the cat will give subtle preliminary warning signals. Look for a twitching tail, tensing of the body, or slightly flattened ears and stop petting your cat immediately when you see them. If the cat does nip, stop petting and keep your hand still. Don't hit the cat as it could become aggressive and bite you seriously. Your cat is probably playing, which is linked to predatory behavior.
Kittens practice hunting by playing.
They stalk, chase, pounce, grab and bite. Sometimes this leads to injury, so such behavior can't be ignored. If you're pounced upon, whip it out quickly onto the floor so the cat can go after it. The most creative toys involve human interaction. Try a child's size fiberglass fishing pole with a 3' long cord that has a sturdy denim tuft at the end.