Typically, natural mechanism is provide rest to any part of the body which has a pain generating source. In case there is any primary injury, spasm of the hamstrings is a protective mechanism of the body to prevent further injury to affected part.
Mostly these can (like other sprains) be treated conservatively with rest, icepacks and electrotherapy regimes. It is imperative to distinguish and identify a primary undeerlying pathology causing the spasm.