There's really no solid one reason why we sometimes cramp when training, most are just theories. The 2 most popular are dehydration or electrolyte imbalances and just pushing oneself beyond your fitness level until training allows your body to adapt to the stress. These arguments make sense as cramps seem more common in the heat when body fluid levels decrease.
I'd like to throw out 2 other reasons that seem to have some merit. One is the result of burning protein for fuel in the absence of available sugar. Some research in this area confirms that subjects with the highest levels of ammonia release during exercise were more likely to experience cramps. High Ammonia levels indicate that higher levels of protein are being used as fuel. Ingesting whey protein before exercise can elevate these ammonia levels. Second, poor patterns of movement during say running or cycling might be causing activation of the Golgi tendon organs. The Golgi tendon reflex protects the skeletal muscle from excessively loads by causing the muscle to relax. These "strain gauges" are built into the tendons to prevent muscle tears. There could be something upsetting the Golgi organs that sets off a cramping pattern.
The only way to deal with a cramp coming on is slow down or try to stretch the muscle out which can be difficult depending if your competing. Of course the other option is pinching your upper lip which some athletes swear by, Odd, but true.